區塊鏈
挖礦,比特幣,EOS,以太坊

EOS開發教程,eosjs使用說明文檔!

eosjs使用說明文檔

本使用說明基于EOSIO 1.0.22版本,最新版的教程請參考這里

版本說明:

Version EOSIO/eosjs Npm EOSIO/eos Docker Node
dawn4.2 tag:?13.x.x npm install eosjs(version 13) tag: dawn-v4.2.0 eosio/eos:20180526 local docker
dawn4.1 tag: 12.x.x npm install eosjs(version 12) tag: dawn-v4.1.0 eosio/eos:20180519 local docker
dawn4 tag: 11.x.x npm install [email protected]?(version 11) tag: dawn-v4.0.0 eosio/eos:dawn-v4.0.0 local docker
DAWN-2018-04-23-ALPHA tag:9.x.x npm install [email protected] tag:DAWN-2018-04-23-ALPHA eosio/eos:DAWN-2018-04-23-ALPHA Docker配置
dawn3 tag:8.x.x npm install [email protected] tag:dawn-v3.0.0 eosio/eos:dawn3x Docker配置
dawn2 branch:dawn2 npm?install?eosjs branch:dawn-2.x eosio/eos:dawn2x Docker配置

支持環境

node v8+ npm 6.1.11

  • 當前最新版本的eosjs為tag:15.0.2,支持eosio 1.0.5-1.0.7
  • Converted some types in format module from unsigned to signed: UDecimalPad -> DecimalPad for example (15.0.1)
  • All asset and extended_asset amounts require exact decimal places (Change 1 SYS to 1.0000 SYS) (15.0.0)
  • Use config.verbose instead of config.debug (14.1.0)

EOSJS

用法:

  1. Eos = require(‘eosjs’) // Eos = require(‘./src’)
  2. // eos = Eos.Localnet() // 本地127.0.0.1:8888
  3. eos = Eos.Testnet() // 調用eos.io測試網絡 testnet at eos.io
  4. // All API methods print help when called with no-arguments.
  5. eos.getBlock() //獲取區塊
  6. // Next, your going to need nodeos running on localhost:8888
  7. // If a callback is not provided, a Promise is returned
  8. eos.getBlock(1).then(result => {console.log(result)})
  9. // Parameters can be sequential or an object
  10. eos.getBlock({block_num_or_id: 1}).then(result => console.log(result))
  11. // Callbacks are similar
  12. callback = (err, res) => {err ? console.error(err) : console.log(res)}
  13. eos.getBlock(1, callback)
  14. eos.getBlock({block_num_or_id: 1}, callback)
  15. // Provide an empty object or a callback if an API call has no arguments
  16. eos.getInfo({}).then(result => {console.log(result)})

API調用的文檔見:

  • chain.json
  • account_history.json

鏈接配置

  1. Eos = require(‘eosjs’) // Eos = require(‘./src’)
  2. // Optional configuration..
  3. config = {
  4. keyProvider: [‘PrivateKeys…’], // WIF string or array of keys..
  5. httpEndpoint: ‘http://127.0.0.1:8888’,
  6. mockTransactions: () => ‘pass’, // or ‘fail’
  7. transactionHeaders: (expireInSeconds, callback) => {
  8. callback(null/*error*/, headers)
  9. },
  10. expireInSeconds: 60,
  11. broadcast: true,
  12. debug: false,
  13. sign: true
  14. }
  15. eos = Eos.Localnet(config)

參數說明:

  • mockTransactions(可選)
    • pass: 不廣播,加裝交易工作
    • fail: 不廣播,加裝交易失敗
    • null|undefined: 廣播(默認)
  • transactionHeaders(可選) 手動設置交易記錄頭,該方法中的callback回調函數每次交易都會被調用。頭記錄的文檔見?eosjs-api#headers

選項

例如:eos.transfer(params, options)

  1. options = {
  2. broadcast: true,
  3. sign: true,
  4. authorization: null
  5. }
  • authorization?{array<auth>|auth}?– 該參數用于在多簽名情況下,識別簽名帳號與權限。用字符串格式,如:[email protected]?或者使用對象,如:object<{actor:account,permission}>
    • 如果不寫,則使用默認的授權
    • 如果提供授權賬戶,則其他賬戶不能被添加
    • 多個賬戶按照賬戶名排序

用法

如果使用測試網絡,需要在keyProvider配置私鑰。

  1. Eos = require(‘eosjs’) // Eos = require(‘./src’)
  2. eos = Eos.Localnet({keyProvider: ‘5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3’})
  3. // Run with no arguments to print usage.
  4. eos.transfer() //顯示用法
  5. // Usage with options (options are always optional)
  6. options = {broadcast: false} //不廣播此筆交易
  7. eos.transfer({from: ‘inita’, to: ‘initb’, quantity: ‘1 EOS, memo: }, options) //從inita發送1個EOS到initb賬戶
  8. // Object or ordered args may be used.
  9. eos.transfer(‘inita’, ‘initb’, ‘2 EOS’, ‘memo’, options)
  10. // A broadcast boolean may be provided as a shortcut for {broadcast: false}
  11. eos.transfer(‘inita’, ‘initb’, ‘1 EOS’, , false)

API方法的參數見?eosio_system

【譯者注】如獲取投票者信息使用?voter_info,獲取區塊節點信息使用?producer_info,發布資產使用?issue,獲取區塊鏈參數使用?blockchain_parameters等等

關于簽名的高級用法,查看?keyProvider,eosjs-keygen?或者?unit test

簡寫規則(Shorthand)

在一些特殊情況下,可以使用簡寫,如資產類Asset和授權類Authority 例如:

  • deposit:?'1 eos'?是?1.0000 EOS的簡寫
  • owner:?'EOS6MRy..'?是?{threshold: 1, keys: [key: 'EOS6MRy..', weight: 1]}?的簡寫
  • recover:?inita?或者?[email protected]?分別是以下的簡寫形式:
  • {{threshold: 1, accounts: [..actor: inita, permission: active, weight: 1]}}
  • [email protected]?將active權限改為other
  1. Eos = require(‘eosjs’) // Eos = require(‘./src’)
  2. initaPrivate = ‘5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3’
  3. initaPublic = ‘EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV’
  4. keyProvider = initaPrivate
  5. eos = Eos.Localnet({keyProvider})
  6. eos.newaccount({
  7. creator: ‘inita’,
  8. name: ‘mynewacct’,
  9. owner: initaPublic,
  10. active: initaPublic,
  11. recovery: ‘inita’
  12. })

智能合約部署

setcode命令會在簽名與廣播前,將WASM的文本智能合約編譯成二進制文件,編譯將使用npm的?binaryen庫,因為默認情況下,因為該庫文件很大,沒有被包括到eosjs中。 安裝binaryen庫:

npm i [email protected]

如果遇到binaryen版本與EOS版本發生不兼容,請參考?problematic?在js源碼中導入binaryen:

  1. binaryen = require(‘binaryen’);
  2. eos = Eos.Testnet({…, binaryen});

一個通過eosjs做代幣發行的完整代碼:(【譯者注:此代碼適用于Dawn2.0版本】)

  1. Eos = require(‘eosjs’)
  2. let {ecc} = Eos.modules
  3. initaPrivate = ‘5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3’;//inita私鑰
  4. currencyPrivate = ecc.seedPrivate(‘currency’);
  5. currencyPublic = ecc.privateToPublic(currencyPrivate);
  6. keyProvider = [initaPrivate, currencyPrivate];
  7. binaryen = require(‘binaryen’);//導入編譯器
  8. eos = Eos.Localnet({keyProvider, binaryen});
  9. eos.newaccount({
  10. creator: ‘inita’,
  11. name: ‘currency’,
  12. owner: currencyPublic,
  13. active: currencyPublic,
  14. recovery: ‘inita’
  15. });
  16. contractDir = `${process.env.HOME}/eosio/dawn3/build/contracts/currency`; //合約所在目錄
  17. wast = fs.readFileSync(`${contractDir}/currency.wast`);//讀取wast文件,wast文件通過eosiocpp編譯
  18. abi = fs.readFileSync(`${contractDir}/currency.abi`);//讀取abi文件
  19. //將智能合約發不到區塊鏈
  20. eos.setcode(‘currency’, 0, 0, wast);
  21. eos.setabi(‘currency’, JSON.parse(abi));
  22. currency = null;
  23. // eos.contract(account<string>, [options], [callback]);
  24. eos.contract(‘currency’).then(contract => currency = contract);//部署合約
  25. // 讓inita賬戶執行該合約,并發行一個代幣CUR
  26. currency.issue(‘inita’, ‘10000.0000 CUR’, {authorization: ‘currency’});

原子操作

區塊鏈級別的原子操作實例:

  1. Eos = require(‘eosjs’)
  2. keyProvider = [
  3. ‘5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3’,
  4. Eos.modules.ecc.seedPrivate(‘currency’)
  5. ]; //keyProvider的又一種寫法
  6. eos = Eos.Localnet({keyProvider});
  7. //如果任何一個操作失敗,所有操作將都失敗
  8. eos.transaction(eos =>
  9. {
  10. eos.transfer(‘inita’, ‘initb’, ‘1 EOS’, );
  11. eos.transfer(‘inita’, ‘initc’, ‘1 EOS’, );
  12. }
  13. // [options],
  14. // [callback]
  15. );
  16. //通過智能合約currency交易資產
  17. eos.transaction(‘currency’, currency => {
  18. currency.transfer(‘inita’, ‘initb’, ‘1 CUR’, );
  19. });
  20. //在一次交易中混合不同資產交易
  21. eos.transaction([‘currency’, ‘eosio’], ({currency, eosio}) => {
  22. currency.transfer(‘inita’, ‘initb’, ‘1 CUR’, );
  23. eosio.transfer(‘inita’, ‘initb’, ‘1 EOS’, );
  24. });
  25. //檢查后在發送
  26. eos.contract(‘currency’).then(currency => {
  27. currency.transaction(cur => {
  28. cur.transfer(‘inita’, ‘initb’, ‘1 CUR’, );
  29. cur.transfer(‘initb’, ‘inita’, ‘1 CUR’, );
  30. });
  31. currency.transfer(‘inita’, ‘initb’, ‘1 CUR’, );
  32. });

手動配置發送transacition

優點,靈活度更高

  1. Eos = require(‘eosjs’)
  2. eos = Eos.Localnet({keyProvider: ‘5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3’});
  3. eos.transaction({
  4. actions: [
  5. {
  6. account: ‘eosio’,
  7. name: ‘transfer’,
  8. authorization: [{
  9. actor: ‘inita’,
  10. permission: ‘active’
  11. }],
  12. data: {
  13. from: ‘inita’,
  14. to: ‘initb’,
  15. quantity: ‘7 EOS’,
  16. memo: ‘testing’
  17. }
  18. }
  19. ]
  20. });

后續開發更新

eosjsnodeos的二進制格式將不斷的版本更新,因此,在運行nodeos時需要添加參數:--skip-transaction-signatures。 另外,注意編譯包配置文件?package.json中的目錄結構指向?./lib,如果要測試時,需要從./src導入import,如下:

  1. Eos = require(‘./src’);
  2. eos = Eos.Localnet(…);

除了以上提到的外,eos實例還可以提供很多信息。

  1. // ‘nonce’ is a struct but could be any type or struct like: uint8 or transaction
  2. nonce = {value: ‘..’}
  3. nonceBuffer = eos.fc.toBuffer(‘nonce’, nonce)
  4. assert.deepEqual(nonce, eos.fc.fromBuffer(‘nonce’, nonceBuffer))
  5. // Serialization for a smart-contract’s Abi:
  6. eos.contract(‘currency’, (error, c) => currency = c)
  7. issue = {to: ‘inita’, quantity: ‘1.0000 CUR’, memo: ‘memo’}
  8. issueBuffer = currency.fc.toBuffer(‘issue’, issue)
  9. assert.deepEqual(issue, currency.fc.fromBuffer(‘issue’, issueBuffer))

相關庫文件參考

以下這些庫已經被無縫集成到了eosjs中,也許可以被單獨拿出來使用:

var {api, ecc, json, Fcbuffer, format} = Eos.modules

  • format?./format.md
    • 區塊鏈名稱驗證
    • 資產類名稱格式化
  • eosjs-api [?Github,?NPM]
    • 遠程訪問EOS區塊鏈節點(nodeos)的API
    • 使用此API可以直接訪問區塊鏈上只讀數據(無需對交易簽名)
  • eosjs-ecc [?Github,?NPM]
    • 提供私鑰、公鑰、簽名管理,AES,加密與解密
    • 驗證公鑰/私鑰
    • 使用EOS兼容的checksums加密/解密
    • 計算用于分享的秘密
  • json {api,?achema}
    • 定義了區塊鏈的json數據操作API
  • eosjs-keygen [?Github,?NPM?]
    • 私鑰與密鑰管理
  • Fcbuffer [?Github,?NPM?]
    • 二進制數據序列化
    • 客戶端對交易二進制碼簽名
    • 允許客戶知道當前簽名情況

區塊鏈瀏覽器

獲取并安裝區塊鏈瀏覽器,通過以下方式安裝EOS測試鏈的區塊鏈瀏覽器。

  1. git clone https://github.com/EOSIO/eosjs.git
  2. cd eosjs
  3. npm install
  4. npm run build_browser

編輯網頁文件

  1. <script src=“eos.js”></script>
  2. <script>
  3. var eos = Eos.Testnet()
  4. //…

——————— 本文來自 q_776355102 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/weixin_39842528/article/details/81098758?utm_source=copy

贊(0)

評論 搶沙發

  • 昵稱 (必填)
  • 郵箱 (必填)
  • 網址
p3试机号99