Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

370 lines
14KB

  1. .. _dev_derovirtualmachine:
  2. DERO Virtual Machine
  3. ====================
  4. DERO Virtual Machine represents entire DERO Smart Contracts eco-system which runs on the DERO block chain.
  5. **Documentation**
  6. DVM is a decentralized platform that runs both public and private smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference.Public Smart contracts are open versions. However, the DVM is being designed to support Private Smart Contracts where everything is hidden, eg parties, and information involved. Smart Contracts are nothing but rules which apply on transacting parties.
  7. Current version of DVM is an interpretor based system to avoid security vulneribilities, issues and compiler backdoors. This also allows easy audits of Smart Contracts for quality,bug-testing and security assurances. DVM supports a new language DVM-BASIC.
  8. DVM apps run on a from scratch custom built privacy supporting, encrypted blockchain, an enormously powerful shared global infrastructure that can move value around and represent the ownership of assets/property without leaking any information.No one knows who owns what and who transferred to whom.
  9. * This enables developers to create puzzles, games, voting, markets, store registries of debts or promises, move funds in accordance with instructions given long in the past (like a will or a futures contract) and many other ideas/things that have not been invented yet, all without a middleman or counterparty risk.
  10. * DVM-BASIC is a contract-oriented, high-level language for implementing smart contracts. It is influenced by GW-BASIC, Visual Basic and C and is designed to target the DERO Virtual Machine (DVM). It is very easy to program and very readable.
  11. * DVM runs Smart Contracts which are a collection of functions written in DVM-BASIC. These functions can be invoked over the blockchain to do something. SCs can act as libraries for other SCs.
  12. * DVM supports number of comments formats such as ', // , /* */ as good documentation is necessary.
  13. **Example Factorial Program**
  14. .. code-block:: php
  15. :linenos:
  16. ' This is a comment
  17. // This comment is supported
  18. /* this is multi-line comment */
  19. Function Factorial(s Uint64) Uint64 // this is a commment
  20. 10 DIM result,scopy as Uint64 /* this is also comment */
  21. 15 LET scopy = s
  22. 20 LET result = 1
  23. 30 LET result = result * s
  24. 40 LET s = s - 1
  25. 50 IF s >= 2 THEN GOTO 30
  26. 60 PRINTF "FACTORIAL of %d = %d" scopy result
  27. 70 RETURN result
  28. End Function
  29. **DVM are written in a DVM-BASIC custom BASIC style language with line numbers.**
  30. **DVM supports uint64 and string data-types.**
  31. **DVM interprets the smart-contract and processes the SC line-line**
  32. * uint64 supports almost all operators namely +,-,*,/,%
  33. * uint64 support following bitwise operators & ,|, ^, ! , >> , <<
  34. * uint64 supports following logical operators >, >= , <, <=, == , !=
  35. * string supports only + operator. string support concatenation with a uint64.
  36. * string supports ==, != logical operators.
  37. * All DVM variables are mandatory to define and are initialized to default values namely 0 and "".
  38. A SC execution must return 0 to persist any changes made during execution. During execution, no panics should occur.
  39. DIM Statement
  40. -------------
  41. DIM stands for data in memory and is used to define variable names within a function
  42. syntax
  43. 10 DIM variable1 as type 20 DIM variable1,variable2 as type
  44. type can be any type supported by DVM
  45. Defining a varible initializes a variable to its ZERO value.
  46. Function statement
  47. ------------------
  48. Function statement is used to define a function. See eg, below for a function which adds 2 numbers
  49. .. code-block:: php
  50. :linenos:
  51. Function ADD(x uint64, y uint64) uint64
  52. 10 RETURN x + y
  53. End Function
  54. Function syntax is of 2 types
  55. 1. Function function_name( 0 or more arguments )
  56. 2. Function function_name( 0 or more arguments ) return type
  57. The rules for functions are as follows
  58. * All functions begin with Function keyword
  59. * Function name should be alpha-numeric. If the first letter of the function is Upper case alphabet, it can be invoked by blockchain and other smart-contracts. Otherwise the function can only be called by other functions within the smart contract.
  60. * Function may or may not have a return type
  61. * All functions must use RETURN to return from function or to return a value. RETURN is mandatory.
  62. * All functions must end with End Function. End Function is mandatory
  63. * A function can have a implicit parameter value of type uint64, which contains amount of DERO value sent with the transaction.
  64. Any error caused during processing will immediately stop execution and discard all changes that occur during SC execution.
  65. Any Entrypoint which returns uint64 value 0 is termed as success and will make transaction to commit all state changes.
  66. GOTO Statement
  67. --------------
  68. It is used to jump to any point within the function. It cannot cross function-boundary
  69. syntax GOTO line-number
  70. IF
  71. --
  72. If statement is used to evaluate expression and make decisions.It has following forms
  73. 1. IF expr1 condition expr2 THEN GOTO line number
  74. 2. IF expr1 condition expr2 THEN GOTO line number ELSE GOTO line number
  75. This is used to change execution flow based on conditions. Conditions can be as complex expressions
  76. LET Statement
  77. -------------
  78. LET is used to assign a value to a variable. value can be as complex as possible and can contain complex expression
  79. syntax
  80. .. code-block:: php
  81. line number LET variable_name = expression;
  82. expression can invoke other functions,eg
  83. 10 LET x = 2 + 3 + ADD(2,3)
  84. ANY assignments within DVM can only be done using LET
  85. Lottery.bas
  86. -------------
  87. .. code-block:: php
  88. :linenos:
  89. /* Lotter Smart Contract in DVM-BASIC
  90. This lottery smart contract will give lottery wins every xth try.
  91. */
  92. Function Lottery(value Uint64) Uint64
  93. 10 dim deposit_count,winner as Uint64
  94. 20 LET deposit_count = LOAD("deposit_count")+1
  95. 25 IF value == 0 THEN GOTO 110 // if deposit amount is 0, simply return
  96. 30 STORE("depositor_address" + (deposit_count-1), SIGNER()) // store address for later on payment
  97. 40 STORE("deposit_total", LOAD("deposit_total") + value )
  98. 50 STORE("deposit_count",deposit_count)
  99. 60 IF LOAD("lotteryeveryXdeposit") > deposit_count THEN GOTO 110 // we will wait till X players join in
  100. // we are here means all players have joined in, roll the DICE,
  101. 70 LET winner = RANDOM() % deposit_count // we have a winner
  102. 80 SEND_DERO_TO_ADDRESS(LOAD("depositor_address" + winner) , LOAD("lotterygiveback")*LOAD("deposit_total")/10000)
  103. // re initialize for another round
  104. 90 STORE("deposit_count", 0) // initial players
  105. 100 STORE("deposit_total", 0) // total deposit of all players
  106. 110 RETURN 0
  107. End Function
  108. // this function is used to initialize parameters during install time
  109. Function Initialize() Uint64
  110. 10 STORE("owner", SIGNER()) // store in DB ["owner"] = address
  111. 20 STORE("lotteryeveryXdeposit", 2) // lottery will reward every X deposits
  112. // how much will lottery giveback in 1/10000 parts, granularity .01 %
  113. 30 STORE("lotterygiveback", 9900) // lottery will give reward 99% of deposits, 1 % is accumulated for owner to withdraw
  114. 33 STORE("deposit_count", 0) // initial players
  115. 34 STORE("deposit_total", 0) // total deposit of all players
  116. 35 printf "Initialize executed"
  117. 40 RETURN 0
  118. End Function
  119. // used to tune lottery parameters
  120. Function TuneLotteryParameters(input Uint64, lotteryeveryXdeposit Uint64, lotterygiveback Uint64) Uint64
  121. 10 dim key,stored_owner as String
  122. 20 dim value_uint64 as Uint64
  123. 30 IF ADDRESS_RAW(LOAD("owner")) == ADDRESS_RAW(SIGNER()) THEN GOTO 100 // check whether owner is real owner
  124. 40 RETURN 1
  125. 100 STORE("lotteryeveryXdeposit", lotteryeveryXdeposit) // lottery will reward every X deposits
  126. 130 STORE("lotterygiveback", value_uint64) // how much will lottery giveback in 1/10000 parts, granularity .01 %
  127. 140 RETURN 0 // return success
  128. End Function
  129. // this function is used to change owner
  130. // owner is an string form of address
  131. Function TransferOwnership(newowner String) Uint64
  132. 10 IF ADDRESS_RAW(LOAD("owner")) == ADDRESS_RAW(SIGNER()) THEN GOTO 30
  133. 20 RETURN 1
  134. 30 STORE("tmpowner",newowner)
  135. 40 RETURN 0
  136. End Function
  137. // until the new owner claims ownership, existing owner remains owner
  138. Function ClaimOwnership() Uint64
  139. 10 IF ADDRESS_RAW(LOAD("tmpowner")) == ADDRESS_RAW(SIGNER()) THEN GOTO 30
  140. 20 RETURN 1
  141. 30 STORE("owner",SIGNER()) // ownership claim successful
  142. 40 RETURN 0
  143. End Function
  144. // if signer is owner, withdraw any requested funds
  145. // if everthing is okay, thety will be showing in signers wallet
  146. Function Withdraw( amount Uint64) Uint64
  147. 10 IF ADDRESS_RAW(LOAD("owner")) == ADDRESS_RAW(SIGNER()) THEN GOTO 30
  148. 20 RETURN 1
  149. 30 SEND_DERO_TO_ADDRESS(SIGNER(),amount)
  150. 40 RETURN 0
  151. End Function
  152. Lotter SC Guide
  153. ---------------
  154. **Dero Stargate DVM Smart Contracts guide to install and test various function of lottery Smart Contract.**
  155. **Download** Dero Stargate testnet `source <https://git.dero.io/DeroProject/derosuite_stargate>`_ and `binaries. <https://git.dero.io/DeroProject/Dero_Stargate_testnet_binaries>`_
  156. .. code-block:: php
  157. ./derod-linux-amd64 --testnet;
  158. **Start DERO wallet in testnet.**
  159. .. code-block:: php
  160. dero-wallet-cli-linux-amd64 --rpc-server --wallet-file testnet.wallet --testnet;
  161. **Start Dero wallet second instance to test transfer/ownership functions etc.**
  162. .. code-block:: php
  163. dero-wallet-cli-linux-amd64 --wallet-file testnet2.wallet --testnet --rpc-server --rpc-bind=127.0.0.1:30308;
  164. **Dero testnet Explorer**
  165. .. code-block:: php
  166. ./explorer-linux-amd64 --rpc-server-address 127.0.0.1:30306 --http-address=0.0.0.0:8080;
  167. **DERO Stargate Testnet Explorer**
  168. https://testnetexplorer.dero.io/
  169. **Installing Smart Contract**
  170. `Download Lottery.bas <https://git.dero.io/DeroProject/derosuite_stargate/src/master/cmd/dvm/lottery.bas>`_
  171. .. code-block:: php
  172. curl --request POST --data-binary @lottery.bas http://127.0.0.1:30309/install_sc;
  173. **Examples of various lottery Smart Contract functions Eg: To play lottery**
  174. .. code-block:: php
  175. curl -X POST http://127.0.0.1:30309/json_rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"0","method":"transfer_split","params":{"mixin":5,"get_tx_key": true , "sc_tx":{"entrypoint":"Lottery","scid":"ab82caa18753efa0f76e7266af7fdd7f11e0ada5e135bd63f1cd823f5e2c2fdc" , "value":4000000000000 } }}';
  176. **Eg: Withdraw balance**
  177. .. code-block:: php
  178. curl -X POST http://127.0.0.1:30309/json_rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"0","method":"transfer_split","params":{"mixin":5,"get_tx_key": true , "sc_tx":{"entrypoint":"Withdraw","scid":"55aaf55b5203cd10f473a9bcf641f305885235e176270ae5e38ba6fa05dbf2b0", "params":{ "amount":"1" } } }}';
  179. **Eg: To transfer ownership**
  180. .. code-block:: php
  181. curl -X POST http://127.0.0.1:30309/json_rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"0","method":"transfer_split","params":{"mixin":5,"get_tx_key": true , "sc_tx":{"entrypoint":"TransferOwnership","scid":"55aaf55b5203cd10f473a9bcf641f305885235e176270ae5e38ba6fa05dbf2b0", "params":{ "newowner":"dETohFmTunwF58wAs5Jn3d1N1oaJqwRxvarNJudUh95nVbZyigTja1W8Ljzp3j8VhxbB9gv3TBs4W5gnFa24cehz2cM6nUg84s" } } }}';
  182. **Eg: To claim ownership**
  183. .. code-block:: php
  184. curl -X POST http://127.0.0.1:30308/json_rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"0","method":"transfer_split","params":{"mixin":;
  185. Return Statement
  186. ----------------
  187. It is used to return from a function and can be used anywhere within a function
  188. syntax
  189. 1. RETURN ( return nil )
  190. 2. RETURN expression ( evaluates expression and returns value )
  191. any return value must match with the type defined while declaring function
  192. Support Functions
  193. -----------------
  194. .. code-block:: php
  195. :linenos:
  196. Support Functions are inbuilt functions which provide some functionality or expose internals for speed and technical reasons.
  197. LOAD(variable)
  198. ==============
  199. LOAD loads a variable which was previously stored in the blockchain using STORE function. Return type will be Uint64/String depending on what is stored.
  200. It will panic if the value does NOT exists
  201. Uint64 EXISTS(variable)
  202. =======================
  203. EXISTS return 1 if the variable is store in DB and 0 otherwise
  204. STORE(key variable, value variable)
  205. ===================================
  206. STORE stores key and value in the DB. All storage state of the SC is accessible only from the SC which created it.
  207. Uint64 RANDOM()
  208. Uint64 RANDOM(limit Uin64)
  209. ============================
  210. RANDOM returns a random using a PRNG seeded on BLID,SCID,TXID. First form gives a uint64, second form returns
  211. random number in the range 0 - (limit), 0 is inclusive, limit is exclusive
  212. String SCID()
  213. ==============
  214. Returns SMART CONTRACT ID which is currently running
  215. String BLID()
  216. ==============
  217. Returns current BLOCK ID which contains current execution-in-progress TXID
  218. String TXID()
  219. =============
  220. Returns current TXID which is execution-in-progress.
  221. Uint64 BLOCK_HEIGHT()
  222. =====================
  223. Returns current chain height of BLID()
  224. Uint64 BLOCK_TOPOHEIGHT()
  225. ===========================
  226. Returns current topoheight of BLID()
  227. String SIGNER()
  228. =================
  229. Returns address of who signed this transaction
  230. Uint64 IS_ADDRESS_VALID(p String)
  231. =================================
  232. Returns 1 is address is valid, 0 otherwise
  233. String ADDRESS_RAW(p String)
  234. ============================
  235. Returns address in RAW form as 64 byte keys, stripping away textual/presentation form. 2 address should always be compared in RAW form
  236. SEND_DERO_TO_ADDRESS(a String, amount Uint64)
  237. ==============================================
  238. Sends amount DERO from SC DERO balance to a address. address must in string form DERO/DETO form
  239. If the SC does not have enough balance, it will panic