基於區塊鏈柚子(EOS)錢包前端插件 scatter
安裝和使用
npm i scatterjs-core scatterjs-plugin-eosjs eosjs -D
//main.js
import ScatterJS from "scatterjs-core";
import ScatterEOS from "scatterjs-plugin-eosjs";
import Eos from "eosjs";
ScatterJS.plugins(new ScatterEOS());
網絡鏈
// EOS公鏈(正式環境)
let main = {
protocol: "https",
blockchain: "eos",
host: "nodes.get-scatter.com",
port: 443,
chainId: "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906"
};
// 測試鏈 (就是用來測試的)
let jungle2 = {
protocol: "http",
blockchain: "eos",
host: "jungle2.cryptolions.io",
port: 80,
chainId: "e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473"
};
調試和配置
翻牆下載scatter插件安裝.
- 打開scatter ---setting--network---新建 把 jungle2 的信息填到對應的位置,(取名隨便取,jungle2) --保存
- 生成秘鑰對,一鍵生成私鑰和公鑰
- 新建測試賬號,需要填入剛才的公鑰,賬號名是z-a,1-5長度12位組合
- 充值,賬號建立成功之后莫有錢, 可以先充值100塊.測試的時候省着點用
- 測試鏈上的賬號建好之后,打開scatter---身份---新建,選擇剛才建立的 network => jungle2,然后選擇對應的賬號. 點導入---保存
這樣scatter 插件配置完畢.可以愉快的開發了.
創建scatter
ScatterJS.scatter.connect("app").then(connected => {
if (!connected) return false;
let scatter = ScatterJS.scatter; //這里就是
window.ScatterJS = null;
window.scatter = null
//通過兩種方式拿到eos 對象
// this.eos = Eos({ httpEndpoint: '', signatureProvider: ScatterJS.scatter.eosHook(jungle2) });
this.eos = scatter.eos(jungle2, Eos, { expireInSeconds: 60 });
//如果授權成功,則可以拿到用戶相關信息
if (scatter.identity) {
this.account = scatter.identity.accounts.find(x => x.blockchain === "eos");
}
});
授權和取消授權
//授權
const requiredFields = { accounts: [jungle2] };
scatter.getIdentity(requiredFields).then(() => {
//分別拿到用戶信息 和 eos 對象
this.account = scatter.identity.accounts.find(x => x.blockchain === "eos");
this.eos = scatter.eos(jungle2, Eos, { expireInSeconds: 60 }, 'https');
}).catch(res=>{
})
//退出
scatter.forgetIdentity().then(id => {
this.account = null;
this.eos = null
});
轉賬交易部分
//取幣種相關信息
let config = {
account: 'xxx', //賬號名稱
code: "eosio.token", //合約名稱
symbol: "ETH" //幣種
};
eos.getCurrencyBalance(config).then(e => {
console.log(e)
});
//取用戶相關信息
eos.getAccount({ account_name: 'xxx' }).then(res => {
// console.log(res)
let totoal = res.core_liquid_balance //余額
let cpu = res.cpu_limit; //CPU
let net = res.net_limit; //NET
});
//發起轉賬
// eos.transfer('發送方帳號', '接收方帳號', '0.3000 DEV','memo', options, callback)
eos.transfer(account.name, user, `${coin} EOS`, memo, transactionOptions).then(trx => {
// That's it!
console.log(`Transaction ID: ${trx.transaction_id}`);
//有transaction_id 就代表轉賬成功了
}).catch(res => {
});
//還可以使用對象
eos.transfer({ from: '發送方帳號', to: '接收方帳號', quantity: '0.1000 DEV', memo: '備注', callback })
交互部分
// 獲取Table行數據
eosjs.getTableRows({"scope":'合約名字', "code":'合約名字', "table":"game", "json": true},callback)
//執行合約上的函數
eos.contract("合約名字").then(actions => { //actions隨便起的變量名
actions.test('hello', { //test是方法名, 'hello'是該actions合約test方法的參數
authorization: [{actor:'lilei'}] //lilei是建立該合約的用戶
}).then(result => {
console.log(result);
});
當然EOS 的 API非常多,但是對於前端而言,以上足夠開發一個線上賭博游戲了.
至於說發代幣啊,部署合約, 抵押,競拍 ,出售 ,購買,新建帳號 這些都用不着, 可以轉給后端.
[完]😁