@alephium/web3 0.0.3 → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.editorconfig +13 -0
  2. package/.eslintignore +2 -0
  3. package/.eslintrc.json +21 -0
  4. package/README.md +2 -2
  5. package/contracts/add.ral +7 -3
  6. package/contracts/greeter.ral +3 -1
  7. package/contracts/greeter_interface.ral +3 -0
  8. package/contracts/greeter_main.ral +9 -0
  9. package/contracts/main.ral +3 -5
  10. package/dev/user.conf +8 -4
  11. package/dist/alephium-web3.min.js +1 -1
  12. package/dist/alephium-web3.min.js.map +1 -1
  13. package/dist/scripts/check-versions.d.ts +1 -0
  14. package/dist/scripts/check-versions.js +39 -0
  15. package/dist/{cli → scripts}/create-project.d.ts +0 -0
  16. package/dist/scripts/create-project.js +124 -0
  17. package/dist/scripts/header.d.ts +0 -0
  18. package/dist/scripts/header.js +18 -0
  19. package/dist/scripts/rename-gitignore.d.ts +1 -0
  20. package/dist/scripts/rename-gitignore.js +24 -0
  21. package/dist/scripts/start-devnet.d.ts +1 -0
  22. package/dist/scripts/start-devnet.js +131 -0
  23. package/dist/scripts/stop-devnet.d.ts +1 -0
  24. package/dist/scripts/stop-devnet.js +32 -0
  25. package/dist/{api → src/api}/api-alephium.d.ts +287 -168
  26. package/dist/{api → src/api}/api-alephium.js +497 -115
  27. package/dist/{api → src/api}/api-explorer.d.ts +117 -19
  28. package/dist/{api → src/api}/api-explorer.js +206 -46
  29. package/dist/src/api/index.d.ts +10 -0
  30. package/dist/src/api/index.js +55 -0
  31. package/dist/{lib → src}/constants.d.ts +0 -0
  32. package/dist/{lib → src}/constants.js +0 -0
  33. package/dist/src/contract/contract.d.ts +182 -0
  34. package/dist/src/contract/contract.js +760 -0
  35. package/dist/src/contract/events.d.ts +29 -0
  36. package/dist/src/contract/events.js +77 -0
  37. package/dist/src/contract/index.d.ts +3 -0
  38. package/dist/src/contract/index.js +32 -0
  39. package/dist/src/contract/ralph.d.ts +12 -0
  40. package/dist/src/contract/ralph.js +362 -0
  41. package/dist/src/index.d.ts +5 -0
  42. package/dist/src/index.js +34 -0
  43. package/dist/src/signer/index.d.ts +2 -0
  44. package/dist/src/signer/index.js +31 -0
  45. package/dist/src/signer/node-wallet.d.ts +13 -0
  46. package/dist/src/signer/node-wallet.js +60 -0
  47. package/dist/src/signer/signer.d.ts +143 -0
  48. package/dist/src/signer/signer.js +184 -0
  49. package/dist/src/test/index.d.ts +7 -0
  50. package/dist/src/test/index.js +41 -0
  51. package/dist/src/test/privatekey-wallet.d.ts +12 -0
  52. package/dist/src/test/privatekey-wallet.js +68 -0
  53. package/dist/{lib → src/utils}/address.d.ts +0 -0
  54. package/dist/{lib → src/utils}/address.js +1 -1
  55. package/dist/{lib → src/utils}/bs58.d.ts +2 -2
  56. package/dist/{lib → src/utils}/bs58.js +3 -1
  57. package/dist/{lib → src/utils}/djb2.d.ts +0 -0
  58. package/dist/{lib → src/utils}/djb2.js +1 -1
  59. package/dist/src/utils/index.d.ts +6 -0
  60. package/dist/src/utils/index.js +35 -0
  61. package/dist/{lib → src/utils}/password-crypto.d.ts +0 -0
  62. package/dist/{lib → src/utils}/password-crypto.js +8 -7
  63. package/dist/src/utils/transaction.d.ts +2 -0
  64. package/dist/src/utils/transaction.js +58 -0
  65. package/dist/src/utils/utils.d.ts +30 -0
  66. package/dist/{lib → src/utils}/utils.js +83 -19
  67. package/gitignore +5 -4
  68. package/package.json +56 -40
  69. package/scripts/create-project.ts +136 -0
  70. package/scripts/header.js +17 -0
  71. package/scripts/start-devnet.js +3 -3
  72. package/src/api/api-alephium.ts +2323 -0
  73. package/src/api/api-explorer.ts +808 -0
  74. package/src/api/index.ts +35 -0
  75. package/src/constants.ts +20 -0
  76. package/src/contract/contract.ts +1014 -0
  77. package/src/contract/events.ts +102 -0
  78. package/src/contract/index.ts +21 -0
  79. package/src/contract/ralph.test.ts +178 -0
  80. package/src/contract/ralph.ts +362 -0
  81. package/src/fixtures/address.json +36 -0
  82. package/src/fixtures/balance.json +9 -0
  83. package/src/fixtures/self-clique.json +19 -0
  84. package/src/fixtures/transaction.json +13 -0
  85. package/src/fixtures/transactions.json +179 -0
  86. package/src/index.ts +24 -0
  87. package/src/signer/fixtures/genesis.json +26 -0
  88. package/src/signer/fixtures/wallets.json +26 -0
  89. package/src/signer/index.ts +20 -0
  90. package/src/signer/node-wallet.ts +74 -0
  91. package/src/signer/signer.ts +313 -0
  92. package/src/test/index.ts +32 -0
  93. package/src/test/privatekey-wallet.ts +58 -0
  94. package/src/utils/address.test.ts +47 -0
  95. package/src/utils/address.ts +39 -0
  96. package/src/utils/bs58.ts +26 -0
  97. package/src/utils/djb2.test.ts +35 -0
  98. package/src/utils/djb2.ts +25 -0
  99. package/src/utils/index.ts +24 -0
  100. package/src/utils/password-crypto.test.ts +27 -0
  101. package/src/utils/password-crypto.ts +77 -0
  102. package/src/utils/transaction.test.ts +50 -0
  103. package/src/utils/transaction.ts +39 -0
  104. package/src/utils/utils.test.ts +160 -0
  105. package/src/utils/utils.ts +209 -0
  106. package/templates/{README.md → base/README.md} +4 -4
  107. package/templates/base/package.json +35 -0
  108. package/templates/base/src/greeter.ts +41 -0
  109. package/templates/base/tsconfig.json +19 -0
  110. package/templates/react/README.md +34 -0
  111. package/templates/react/config-overrides.js +18 -0
  112. package/templates/react/package.json +66 -0
  113. package/templates/react/src/App.tsx +42 -0
  114. package/templates/react/src/artifacts/greeter.ral.json +26 -0
  115. package/templates/react/src/artifacts/greeter_main.ral.json +22 -0
  116. package/templates/shared/.eslintrc.json +12 -0
  117. package/templates/shared/scripts/header.js +0 -0
  118. package/test/contract.test.ts +161 -0
  119. package/test/events.test.ts +139 -0
  120. package/webpack.config.js +1 -1
  121. package/contracts/greeter-main.ral +0 -8
  122. package/dist/cli/create-project.js +0 -87
  123. package/dist/lib/clique.d.ts +0 -23
  124. package/dist/lib/clique.js +0 -149
  125. package/dist/lib/contract.d.ts +0 -152
  126. package/dist/lib/contract.js +0 -711
  127. package/dist/lib/explorer.d.ts +0 -8
  128. package/dist/lib/explorer.js +0 -46
  129. package/dist/lib/index.d.ts +0 -12
  130. package/dist/lib/index.js +0 -60
  131. package/dist/lib/node.d.ts +0 -10
  132. package/dist/lib/node.js +0 -64
  133. package/dist/lib/numbers.d.ts +0 -7
  134. package/dist/lib/numbers.js +0 -128
  135. package/dist/lib/signer.d.ts +0 -17
  136. package/dist/lib/signer.js +0 -70
  137. package/dist/lib/storage-browser.d.ts +0 -9
  138. package/dist/lib/storage-browser.js +0 -52
  139. package/dist/lib/storage-node.d.ts +0 -9
  140. package/dist/lib/storage-node.js +0 -65
  141. package/dist/lib/utils.d.ts +0 -11
  142. package/dist/lib/wallet.d.ts +0 -30
  143. package/dist/lib/wallet.js +0 -142
  144. package/templates/package.json +0 -29
@@ -0,0 +1,34 @@
1
+ # My dApp
2
+
3
+ ## Install
4
+
5
+ ```
6
+ npm install
7
+ ```
8
+
9
+ ## Start the app
10
+
11
+ Compile the TypeScript files into JavaScript:
12
+
13
+ ```
14
+ npm run start
15
+ ```
16
+
17
+ ## Start a devnet
18
+
19
+ ```
20
+ npm run start-devnet // this will start a devnet for smart contract tests
21
+ ```
22
+
23
+ ## Stop/restart devnet
24
+
25
+ ```
26
+ npm run stop-devnet
27
+ npm run restart-devnet
28
+ ```
29
+
30
+ ## Testing
31
+
32
+ ```
33
+ npm test
34
+ ```
@@ -0,0 +1,18 @@
1
+ const webpack = require('webpack')
2
+
3
+ module.exports = function override(config) {
4
+ const fallback = config.resolve.fallback || {}
5
+ Object.assign(fallback, {
6
+ fs: false,
7
+ crypto: require.resolve('crypto-browserify'),
8
+ stream: require.resolve('stream-browserify')
9
+ })
10
+ config.resolve.fallback = fallback
11
+ config.plugins = (config.plugins || []).concat([
12
+ new webpack.ProvidePlugin({
13
+ process: 'process/browser',
14
+ Buffer: ['buffer', 'Buffer']
15
+ })
16
+ ])
17
+ return config
18
+ }
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "my-dapp",
3
+ "version": "0.1.0",
4
+ "config": {
5
+ "alephium_version": "1.4.0-rc2"
6
+ },
7
+ "dependencies": {
8
+ "@testing-library/jest-dom": "^5.16.4",
9
+ "@testing-library/react": "^13.0.1",
10
+ "@testing-library/user-event": "^13.5.0",
11
+ "@types/jest": "^27.4.1",
12
+ "@types/node": "^16.11.26",
13
+ "@types/react": "^18.0.3",
14
+ "@types/react-dom": "^18.0.0",
15
+ "@alephium/web3": "0.1.0-rc.0",
16
+ "react": "^18.0.0",
17
+ "react-dom": "^18.0.0",
18
+ "react-scripts": "5.0.1",
19
+ "typescript": "^4.6.3",
20
+ "web-vitals": "^2.1.4"
21
+ },
22
+ "scripts": {
23
+ "start": "react-app-rewired start",
24
+ "build": "react-app-rewired build",
25
+ "test": "react-app-rewired test",
26
+ "eject": "react-scripts eject",
27
+ "lint": "eslint . --ext ts",
28
+ "prettier": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\""
29
+ },
30
+ "eslintConfig": {
31
+ "extends": [
32
+ "react-app",
33
+ "react-app/jest"
34
+ ]
35
+ },
36
+ "browserslist": {
37
+ "production": [
38
+ ">0.2%",
39
+ "not dead",
40
+ "not op_mini all"
41
+ ],
42
+ "development": [
43
+ "last 1 chrome version",
44
+ "last 1 firefox version",
45
+ "last 1 safari version"
46
+ ]
47
+ },
48
+ "devDependencies": {
49
+ "buffer": "^6.0.3",
50
+ "crypto-browserify": "^3.12.0",
51
+ "eslint-config-prettier": "^8.5.0",
52
+ "process": "^0.11.10",
53
+ "react-app-rewired": "^2.2.1",
54
+ "stream-browserify": "^3.0.0"
55
+ },
56
+ "prettier": {
57
+ "printWidth": 120,
58
+ "tabWidth": 2,
59
+ "useTabs": false,
60
+ "semi": false,
61
+ "singleQuote": true,
62
+ "jsxSingleQuote": true,
63
+ "bracketSameLine": false,
64
+ "trailingComma": "none"
65
+ }
66
+ }
@@ -0,0 +1,42 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import './App.css'
3
+
4
+ import { explorer, Contract, Script } from '@alephium/web3'
5
+ import contractJson from './artifacts/greeter.ral.json'
6
+ import scriptJson from './artifacts/greeter_main.ral.json'
7
+
8
+ function Dashboard() {
9
+ const api = new explorer.Api<null>({ baseUrl: 'https://mainnet-backend.alephium.org' })
10
+ const contract = Contract.fromJson(contractJson).toString()
11
+ const script = Script.fromJson(scriptJson).toString()
12
+ const [blocks, setBlocks] = useState('')
13
+
14
+ useEffect(() => {
15
+ async function fetchBlocks() {
16
+ const blocks = (await api.blocks.getBlocks({ page: 1 })).total
17
+ setBlocks(JSON.stringify(blocks))
18
+ }
19
+
20
+ fetchBlocks()
21
+ })
22
+
23
+ return (
24
+ <div>
25
+ <p>blocks: {blocks}</p>
26
+ <p>contract: {contract}</p>
27
+ <p>script: {script}</p>
28
+ </div>
29
+ )
30
+ }
31
+
32
+ function App() {
33
+ return (
34
+ <div className='App'>
35
+ <header className='App-header'>
36
+ <Dashboard />
37
+ </header>
38
+ </div>
39
+ )
40
+ }
41
+
42
+ export default App
@@ -0,0 +1,26 @@
1
+ {
2
+ "sourceCodeSha256": "10fe90ccf08b6b3fd2a653bd4258628f5dd165788cc48a83f9d6ff8039404588",
3
+ "functions": [
4
+ {
5
+ "name": "greet",
6
+ "signature": "pub greet()->(U256)",
7
+ "argNames": [],
8
+ "argTypes": [],
9
+ "returnTypes": [
10
+ "U256"
11
+ ]
12
+ }
13
+ ],
14
+ "bytecode": "010109010000000102a00002",
15
+ "codeHash": "39debc1122591f4c96e2f807632acc6d137ea9bba303a4e04476cd8cade35242",
16
+ "fieldsSig": {
17
+ "signature": "TxContract Greeter(btcPrice:U256)",
18
+ "names": [
19
+ "btcPrice"
20
+ ],
21
+ "types": [
22
+ "U256"
23
+ ]
24
+ },
25
+ "eventsSig": []
26
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "sourceCodeSha256": "c1f3b4c4a8c6832d0c9b3e2c7c623de85331d8b0d853daf2acc4288e5655aff7",
3
+ "functions": [
4
+ {
5
+ "name": "main",
6
+ "signature": "pub payable main()->()",
7
+ "argNames": [],
8
+ "argTypes": [],
9
+ "returnTypes": []
10
+ }
11
+ ],
12
+ "bytecodeTemplate": "0101010002000e{0}1700160001000d2f4d{0}1701160101000d2f4d",
13
+ "fieldsSig": {
14
+ "signature": "TxScript Main(greeterContractId:ByteVec)",
15
+ "names": [
16
+ "greeterContractId"
17
+ ],
18
+ "types": [
19
+ "ByteVec"
20
+ ]
21
+ }
22
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": ["prettier", "plugin:react/recommended"],
3
+ "rules": {
4
+ "header/header": [0]
5
+ },
6
+ "parserOptions": {
7
+ "project": "tsconfig.json",
8
+ "ecmaVersion": 2020,
9
+ "sourceType": "module"
10
+ },
11
+ "parser": "@typescript-eslint/parser"
12
+ }
File without changes
@@ -0,0 +1,161 @@
1
+ /*
2
+ Copyright 2018 - 2022 The Alephium Authors
3
+ This file is part of the alephium project.
4
+
5
+ The library is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Lesser General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ The library is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Lesser General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Lesser General Public License
16
+ along with the library. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ import * as fs from 'fs'
20
+ import * as path from 'path'
21
+
22
+ import { NodeProvider } from '../src/api'
23
+ import { Contract, Script, TestContractParams } from '../src/contract'
24
+ import { testWallet } from '../src/test'
25
+
26
+ describe('contract', function () {
27
+ async function testSuite1() {
28
+ const provider = new NodeProvider('http://127.0.0.1:22973')
29
+
30
+ const add = await Contract.fromSource(provider, 'add.ral')
31
+ const sub = await Contract.fromSource(provider, 'sub.ral')
32
+
33
+ const subState = sub.toState({ result: 0 }, { alphAmount: BigInt('1000000000000000000') })
34
+ const testParams: TestContractParams = {
35
+ initialFields: { subContractId: subState.contractId, result: 0 },
36
+ testArgs: { array: [2, 1] },
37
+ existingContracts: [subState]
38
+ }
39
+ const testResult = await add.testPublicMethod(provider, 'add', testParams)
40
+ expect(testResult.returns).toEqual([[3, 1]])
41
+ expect(testResult.contracts[0].codeHash).toEqual(sub.codeHash)
42
+ expect(testResult.contracts[0].fields.result).toEqual(1)
43
+ expect(testResult.contracts[1].codeHash).toEqual(add.codeHash)
44
+ expect(testResult.contracts[1].fields.subContractId).toEqual(subState.contractId)
45
+ expect(testResult.contracts[1].fields.result).toEqual(3)
46
+ const events = testResult.events.sort((a, b) => a.name.localeCompare(b.name))
47
+ expect(events[0].name).toEqual('Add')
48
+ expect(events[0].fields.x).toEqual(2)
49
+ expect(events[0].fields.y).toEqual(1)
50
+ expect(events[1].name).toEqual('Sub')
51
+ expect(events[1].fields.x).toEqual(2)
52
+ expect(events[1].fields.y).toEqual(1)
53
+
54
+ const testResultPrivate = await add.testPrivateMethod(provider, 'addPrivate', testParams)
55
+ expect(testResultPrivate.returns).toEqual([[3, 1]])
56
+
57
+ const signer = await testWallet(provider)
58
+
59
+ const subDeployTx = await sub.transactionForDeployment(signer, {
60
+ initialFields: { result: 0 },
61
+ initialTokenAmounts: []
62
+ })
63
+ const subContractId = subDeployTx.contractId
64
+ expect(subDeployTx.fromGroup).toEqual(0)
65
+ expect(subDeployTx.toGroup).toEqual(0)
66
+ const subSubmitResult = await signer.submitTransaction(subDeployTx.unsignedTx, subDeployTx.txId)
67
+ expect(subSubmitResult.fromGroup).toEqual(0)
68
+ expect(subSubmitResult.toGroup).toEqual(0)
69
+ expect(subSubmitResult.txId).toEqual(subDeployTx.txId)
70
+
71
+ const addDeployTx = await add.transactionForDeployment(signer, {
72
+ initialFields: { subContractId: subContractId, result: 0 },
73
+ initialTokenAmounts: []
74
+ })
75
+ expect(addDeployTx.fromGroup).toEqual(0)
76
+ expect(addDeployTx.toGroup).toEqual(0)
77
+ const addSubmitResult = await signer.submitTransaction(addDeployTx.unsignedTx, addDeployTx.txId)
78
+ expect(addSubmitResult.fromGroup).toEqual(0)
79
+ expect(addSubmitResult.toGroup).toEqual(0)
80
+ expect(addSubmitResult.txId).toEqual(addDeployTx.txId)
81
+
82
+ const addContractId = addDeployTx.contractId
83
+ const main = await Script.fromSource(provider, 'main.ral')
84
+
85
+ const mainScriptTx = await main.transactionForDeployment(signer, {
86
+ initialFields: { addContractId: addContractId }
87
+ })
88
+ expect(mainScriptTx.fromGroup).toEqual(0)
89
+ expect(mainScriptTx.toGroup).toEqual(0)
90
+ const mainSubmitResult = await signer.submitTransaction(mainScriptTx.unsignedTx, mainScriptTx.txId)
91
+ expect(mainSubmitResult.fromGroup).toEqual(0)
92
+ expect(mainSubmitResult.toGroup).toEqual(0)
93
+ }
94
+
95
+ async function testSuite2() {
96
+ const provider = new NodeProvider('http://127.0.0.1:22973')
97
+
98
+ const greeter = await Contract.fromSource(provider, 'greeter.ral')
99
+
100
+ const testParams: TestContractParams = {
101
+ initialFields: { btcPrice: 1 }
102
+ }
103
+ const testResult = await greeter.testPublicMethod(provider, 'greet', testParams)
104
+ expect(testResult.returns).toEqual([1])
105
+ expect(testResult.contracts[0].codeHash).toEqual(greeter.codeHash)
106
+ expect(testResult.contracts[0].fields.btcPrice).toEqual(1)
107
+
108
+ const signer = await testWallet(provider)
109
+
110
+ const deployTx = await greeter.transactionForDeployment(signer, {
111
+ initialFields: { btcPrice: 1 },
112
+ initialTokenAmounts: []
113
+ })
114
+ expect(deployTx.fromGroup).toEqual(0)
115
+ expect(deployTx.toGroup).toEqual(0)
116
+ const submitResult = await signer.submitTransaction(deployTx.unsignedTx, deployTx.txId)
117
+ expect(submitResult.fromGroup).toEqual(0)
118
+ expect(submitResult.toGroup).toEqual(0)
119
+ expect(submitResult.txId).toEqual(deployTx.txId)
120
+
121
+ const greeterContractId = deployTx.contractId
122
+ const main = await Script.fromSource(provider, 'greeter_main.ral')
123
+
124
+ const mainScriptTx = await main.transactionForDeployment(signer, {
125
+ initialFields: { greeterContractId: greeterContractId }
126
+ })
127
+ expect(mainScriptTx.fromGroup).toEqual(0)
128
+ expect(mainScriptTx.toGroup).toEqual(0)
129
+ const mainSubmitResult = await signer.submitTransaction(mainScriptTx.unsignedTx, mainScriptTx.txId)
130
+ expect(mainSubmitResult.fromGroup).toEqual(0)
131
+ expect(mainSubmitResult.toGroup).toEqual(0)
132
+ }
133
+
134
+ it('should test contracts', async () => {
135
+ await testSuite1()
136
+ await testSuite2()
137
+ })
138
+
139
+ function loadJson(fileName: string) {
140
+ const filePath = path.resolve(process.cwd() + path.sep + fileName)
141
+ const rawData = fs.readFileSync(filePath).toString()
142
+ return JSON.parse(rawData)
143
+ }
144
+
145
+ function loadContract(fileName: string) {
146
+ Contract.fromJson(loadJson(fileName))
147
+ }
148
+
149
+ function loadScript(fileName: string) {
150
+ Script.fromJson(loadJson(fileName))
151
+ }
152
+
153
+ it('should load contract from json', async () => {
154
+ loadContract('./artifacts/add.ral.json')
155
+ loadContract('./artifacts/sub.ral.json')
156
+ loadScript('./artifacts/main.ral.json')
157
+
158
+ loadContract('./artifacts/greeter.ral.json')
159
+ loadScript('./artifacts/greeter_main.ral.json')
160
+ })
161
+ })
@@ -0,0 +1,139 @@
1
+ /*
2
+ Copyright 2018 - 2022 The Alephium Authors
3
+ This file is part of the alephium project.
4
+
5
+ The library is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Lesser General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ The library is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Lesser General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Lesser General Public License
16
+ along with the library. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ import { NodeProvider } from '../src/api'
20
+ import { subscribe, Subscription } from '../src/contract/events'
21
+ import { Contract, Script } from '../src/contract'
22
+ import { NodeWallet, SignExecuteScriptTxParams } from '../src/signer'
23
+ import { node } from '../src/api'
24
+ import { testWallet } from '../src/test'
25
+
26
+ describe('events', function () {
27
+ async function deployContract(provider: NodeProvider, signer: NodeWallet): Promise<[string, string]> {
28
+ const sub = await Contract.fromSource(provider, 'sub.ral')
29
+ const subDeployTx = await sub.transactionForDeployment(signer, {
30
+ initialFields: { result: 0 },
31
+ initialTokenAmounts: []
32
+ })
33
+ const subContractId = subDeployTx.contractId
34
+ const subSubmitResult = await signer.submitTransaction(subDeployTx.unsignedTx, subDeployTx.txId)
35
+ expect(subSubmitResult.txId).toEqual(subDeployTx.txId)
36
+
37
+ const add = await Contract.fromSource(provider, 'add.ral')
38
+ const addDeployTx = await add.transactionForDeployment(signer, {
39
+ initialFields: { subContractId: subContractId, result: 0 },
40
+ initialTokenAmounts: []
41
+ })
42
+ const addSubmitResult = await signer.submitTransaction(addDeployTx.unsignedTx, addDeployTx.txId)
43
+ expect(addSubmitResult.txId).toEqual(addDeployTx.txId)
44
+ return [addDeployTx.contractAddress, addDeployTx.contractId]
45
+ }
46
+
47
+ async function executeScript(params: SignExecuteScriptTxParams, signer: NodeWallet, times: number) {
48
+ for (let i = 0; i < times; i++) {
49
+ const scriptTx = await signer.buildScriptTx(params)
50
+ await signer.submitTransaction(scriptTx.unsignedTx, scriptTx.txId)
51
+ }
52
+ }
53
+
54
+ it('should subscribe contract events', async () => {
55
+ const provider = new NodeProvider('http://127.0.0.1:22973')
56
+ const signer = await testWallet(provider)
57
+
58
+ const [contractAddress, contractId] = await deployContract(provider, signer)
59
+ const events: Array<node.ContractEvent> = []
60
+ const subscriptOptions = {
61
+ provider: provider,
62
+ contractAddress: contractAddress,
63
+ pollingInterval: 500,
64
+ eventCallback: (event: node.ContractEvent): Promise<void> => {
65
+ events.push(event)
66
+ return Promise.resolve()
67
+ },
68
+ errorCallback: (error: any, subscription: Subscription): Promise<void> => {
69
+ console.log(error)
70
+ subscription.unsubscribe()
71
+ return Promise.resolve()
72
+ }
73
+ }
74
+ const subscription = subscribe(subscriptOptions)
75
+ const script = await Script.fromSource(provider, 'main.ral')
76
+ const scriptTxParams = await script.paramsForDeployment({
77
+ initialFields: { addContractId: contractId },
78
+ signerAddress: (await signer.getAccounts())[0].address
79
+ })
80
+ await executeScript(scriptTxParams, signer, 3)
81
+ await new Promise((resolve) => setTimeout(resolve, 3000))
82
+
83
+ expect(events.length).toEqual(3)
84
+ events.forEach((event) => {
85
+ expect(event.fields).toEqual([
86
+ { type: 'U256', value: '2' },
87
+ { type: 'U256', value: '1' }
88
+ ])
89
+ })
90
+ expect(subscription.currentEventCount()).toEqual(events.length)
91
+
92
+ subscription.unsubscribe()
93
+ })
94
+
95
+ it('should cancel event subscription', async () => {
96
+ const provider = new NodeProvider('http://127.0.0.1:22973')
97
+ const signer = await testWallet(provider)
98
+
99
+ const [contractAddress, contractId] = await deployContract(provider, signer)
100
+ const events: Array<node.ContractEvent> = []
101
+ const subscriptOptions = {
102
+ provider: provider,
103
+ contractAddress: contractAddress,
104
+ pollingInterval: 500,
105
+ eventCallback: (event: node.ContractEvent): Promise<void> => {
106
+ events.push(event)
107
+ return Promise.resolve()
108
+ },
109
+ errorCallback: (error: any, subscription: Subscription): Promise<void> => {
110
+ console.log(error)
111
+ subscription.unsubscribe()
112
+ return Promise.resolve()
113
+ }
114
+ }
115
+ const subscription = subscribe(subscriptOptions)
116
+ const script = await Script.fromSource(provider, 'main.ral')
117
+ const scriptTx0 = await script.transactionForDeployment(signer, {
118
+ initialFields: { addContractId: contractId }
119
+ })
120
+ await signer.submitTransaction(scriptTx0.unsignedTx, scriptTx0.txId)
121
+ await new Promise((resolve) => setTimeout(resolve, 1500))
122
+ subscription.unsubscribe()
123
+
124
+ expect(events.length).toEqual(1)
125
+ expect(events[0].txId).toEqual(scriptTx0.txId)
126
+ expect(events[0].fields).toEqual([
127
+ { type: 'U256', value: '2' },
128
+ { type: 'U256', value: '1' }
129
+ ])
130
+ expect(subscription.currentEventCount()).toEqual(events.length)
131
+
132
+ const scriptTx1 = await script.transactionForDeployment(signer, {
133
+ initialFields: { addContractId: contractId }
134
+ })
135
+ await signer.submitTransaction(scriptTx1.unsignedTx, scriptTx1.txId)
136
+ await new Promise((resolve) => setTimeout(resolve, 1500))
137
+ expect(events.length).toEqual(1)
138
+ })
139
+ })
package/webpack.config.js CHANGED
@@ -21,7 +21,7 @@ const webpack = require('webpack')
21
21
  module.exports = {
22
22
  mode: 'production',
23
23
  entry: {
24
- alephium: './dist/lib/index.js'
24
+ alephium: './dist/src/index.js'
25
25
  },
26
26
  plugins: [
27
27
  new webpack.SourceMapDevToolPlugin({ filename: '[file].map' }),
@@ -1,8 +0,0 @@
1
- import "greeter.ral"
2
-
3
- TxScript Main {
4
- pub payable fn main() -> () {
5
- let greeter = Greeter(#{{ greeterAddress }})
6
- assert!(greeter.greet() == 1)
7
- }
8
- }
@@ -1,87 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /*
4
- Copyright 2018 - 2022 The Alephium Authors
5
- This file is part of the alephium project.
6
-
7
- The library is free software: you can redistribute it and/or modify
8
- it under the terms of the GNU Lesser General Public License as published by
9
- the Free Software Foundation, either version 3 of the License, or
10
- (at your option) any later version.
11
-
12
- The library is distributed in the hope that it will be useful,
13
- but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- GNU Lesser General Public License for more details.
16
-
17
- You should have received a copy of the GNU Lesser General Public License
18
- along with the library. If not, see <http://www.gnu.org/licenses/>.
19
- */
20
- var __importDefault = (this && this.__importDefault) || function (mod) {
21
- return (mod && mod.__esModule) ? mod : { "default": mod };
22
- };
23
- Object.defineProperty(exports, "__esModule", { value: true });
24
- const fs_extra_1 = __importDefault(require("fs-extra"));
25
- const process_1 = __importDefault(require("process"));
26
- const path_1 = __importDefault(require("path"));
27
- const find_up_1 = __importDefault(require("find-up"));
28
- const chalk_1 = __importDefault(require("chalk"));
29
- function getPackageRoot() {
30
- const packageJsonPath = find_up_1.default.sync('package.json', { cwd: path_1.default.dirname(__filename) });
31
- if (packageJsonPath) {
32
- return path_1.default.dirname(packageJsonPath);
33
- }
34
- else {
35
- throw new Error('Cannot find `package.json`');
36
- }
37
- }
38
- const packageRoot = getPackageRoot();
39
- const projectParent = process_1.default.cwd();
40
- const projectName = process_1.default.argv[2];
41
- if (!projectName) {
42
- console.log('Please provide a project name');
43
- console.log(` ${chalk_1.default.cyan('alephium')} ${chalk_1.default.green('<project-name>')}`);
44
- console.log();
45
- console.log('For example:');
46
- console.log(` ${chalk_1.default.cyan('alephium')} ${chalk_1.default.green('my-alephium-dapp')}`);
47
- console.log();
48
- process_1.default.exit(1);
49
- }
50
- const projectRoot = path_1.default.join(projectParent, projectName);
51
- if (fs_extra_1.default.existsSync(projectRoot)) {
52
- console.log(`Project ${projectName} already exists. Try a different name.`);
53
- console.log();
54
- process_1.default.exit(1);
55
- }
56
- console.log('Copying files');
57
- console.log(` from ${packageRoot}`);
58
- console.log(` to ${projectRoot}`);
59
- console.log('...');
60
- function copy(dir, files) {
61
- const packageDevDir = path_1.default.join(packageRoot, dir);
62
- const projectDevDir = path_1.default.join(projectRoot, dir);
63
- fs_extra_1.default.mkdirSync(projectDevDir);
64
- for (const file of files) {
65
- fs_extra_1.default.copyFileSync(path_1.default.join(packageDevDir, file), path_1.default.join(projectDevDir, file));
66
- }
67
- }
68
- copy('', ['.gitattributes']);
69
- copy('dev', ['user.conf']);
70
- copy('scripts', ['start-devnet.js', 'stop-devnet.js']);
71
- copy('contracts', ['greeter.ral', 'greeter-main.ral']);
72
- fs_extra_1.default.mkdirSync(path_1.default.join(projectRoot, 'src'));
73
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'gitignore'), path_1.default.join(projectRoot, '.gitignore'));
74
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates', 'package.json'), path_1.default.join(projectRoot, 'package.json'));
75
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates', 'tsconfig.json'), path_1.default.join(projectRoot, 'tsconfig.json'));
76
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates', 'README.md'), path_1.default.join(projectRoot, 'README.md'));
77
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates', 'greeter.ts'), path_1.default.join(projectRoot, 'src', 'greeter.ts'));
78
- console.log('✅ Done.');
79
- console.log();
80
- console.log('✨ Project is initialized!');
81
- console.log();
82
- console.log('Next steps:');
83
- console.log(` ${chalk_1.default.cyan(`cd ${projectName}`)}`);
84
- console.log(` ${chalk_1.default.cyan('npm install')}`);
85
- console.log(` ${chalk_1.default.cyan('npm run compile')}`);
86
- console.log(` ${chalk_1.default.cyan('npm run devnet:start')}`);
87
- console.log(` ${chalk_1.default.cyan('node dist/greeter.js')}`);
@@ -1,23 +0,0 @@
1
- import * as api from '../api/api-alephium';
2
- import { Api, SelfClique } from '../api/api-alephium';
3
- import { NodeClient } from './node';
4
- /**
5
- * Clique Client
6
- */
7
- export declare class CliqueClient extends Api<null> {
8
- clique: SelfClique;
9
- clients: NodeClient[];
10
- init(isMultiNodesClique: boolean): Promise<void>;
11
- static convert<T>(response: api.HttpResponse<T, {
12
- detail: string;
13
- }>): T;
14
- selfClique(): Promise<api.HttpResponse<api.SelfClique, api.BadRequest | api.InternalServerError | api.NotFound | api.ServiceUnavailable | api.Unauthorized>>;
15
- getClientIndex(address: string): number;
16
- getBalance(address: string): Promise<api.HttpResponse<api.Balance, api.BadRequest | api.InternalServerError | api.NotFound | api.ServiceUnavailable | api.Unauthorized>>;
17
- getWebSocket(node_i: number): WebSocket | undefined;
18
- transactionCreate(fromAddress: string, fromPublicKey: string, toAddress: string, amount: string, lockTime?: number, gas?: number, gasPrice?: string): Promise<api.HttpResponse<api.BuildTransactionResult, api.BadRequest | api.InternalServerError | api.NotFound | api.ServiceUnavailable | api.Unauthorized>>;
19
- transactionConsolidateUTXOs(fromPublicKey: string, fromAddress: string, toAddress: string): Promise<api.HttpResponse<api.BuildSweepAddressTransactionsResult, api.BadRequest | api.InternalServerError | api.NotFound | api.ServiceUnavailable | api.Unauthorized>>;
20
- transactionSend(fromAddress: string, tx: string, signature: string): Promise<api.HttpResponse<api.TxResult, api.BadRequest | api.InternalServerError | api.NotFound | api.ServiceUnavailable | api.Unauthorized>>;
21
- transactionSign(txHash: string, privateKey: string): string;
22
- transactionVerifySignature(txHash: string, publicKey: string, signature: string): boolean;
23
- }