EOS钱包开发:买入卖出RAM
华胥
发表于 2022-12-6 18:51:38
144
0
0
现在我们能获取到了基于测试网络的账号的网络资源数据,现在我们就介绍如何交易RAM。
交易RAM的前提是我们需要知道它的价格,即买1KB内存需要花费多少EOS,卖1个EOS能获取多少内存。这就需要我们去链上查询数据库获取相应的实时的数据,再进行计算拿到单价。下面我们来一步步实现,最后展示在项目中的相应源码。' C0 ^4 r; E S' l! b Y V
一、获取全网RAM数量% d$ M: t, i( g
全网RAM数量的数据是存在数据库中的,需要使用eosjs库的getTableRows方法获取,或者RPC的chain/get_table_rows接口获取。下面会有eosjs进行交易,所以本章我们统一使用eosjs访问数据,可以到官网查看eosjs-api接口文档。1 U. Z" w7 H6 A: m: f5 t2 Q
首先访问主网中RAM的数量。6 E+ ~, e4 A/ e0 q7 L8 b
Eos = require('eosjs')
eosconfig = {
httpEndpoint: 'https://node1.zbeos.com',
chainId: 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906',
// keyProvider: privatekeyList, // WIF string or array of keys..
expireInSeconds: 60,
broadcast: true,1 q% k X7 i6 ]: d6 }
verbose: false, // API activity: ]- b _1 X* i* {: I# g
sign: true
},% D v. s8 a; }" @6 `( b
eos = Eos(eosconfig)% R4 @! c! S1 o( |( a
eos.getTableRows(true,"eosio","eosio","global").then(result => {
console.log(result)/ j6 a) Y( P3 X C/ {6 ^
}) Y7 R) v, m G9 }( T/ m
输出如下' _/ q7 E' V2 i3 K2 B i* w# V
{ rows:
[ { max_block_net_usage: 1048576,. b9 f o# L( _) Z
target_block_net_usage_pct: 1000,' V, B, w9 l: [- c
max_transaction_net_usage: 524288,: C! W5 f5 v$ C5 L4 ^
base_per_transaction_net_usage: 12,# E, ~7 F, ^, Y; o+ K9 u
net_usage_leeway: 500,
context_free_discount_net_usage_num: 20,: `, `4 c, e" g: V; C
context_free_discount_net_usage_den: 100,
max_block_cpu_usage: 200000,
target_block_cpu_usage_pct: 2000,
max_transaction_cpu_usage: 150000,9 G9 x, p& `; g6 ~) H7 _ H
min_transaction_cpu_usage: 100,
max_transaction_lifetime: 3600,
deferred_trx_expiration_window: 600,
max_transaction_delay: 3888000,+ X; E& a2 J0 l1 b
max_inline_action_size: 4096,
max_inline_action_depth: 4,
max_authority_depth: 6,
max_ram_size: '88414727168',2 @& s. C3 _: R. t& Y6 G" {
total_ram_bytes_reserved: '49777052734',
total_ram_stake: '26261375993',* t* l! l: E& o; z n
last_producer_schedule_update: '2018-11-05T06:57:51.000',
last_pervote_bucket_fill: '1541399606000000',( S* R2 s K' [. J
pervote_bucket: 219209992,
perblock_bucket: 36804696,8 X/ o/ @" ?# e' B0 w Z
total_unpaid_blocks: 95761,
total_activated_stake: '4035546740321',0 ]* A( T/ a" V1 D# `$ f
thresh_activated_stake_time: '1529505892000000',
last_producer_schedule_size: 21,
total_producer_vote_weight: '24124687214114213888.00000000000000000',- n$ e9 n( v. F6 a- V% X( }* z
last_name_close: '2018-11-05T02:08:26.000' } ],2 v# ?* [" k+ d% ]! m8 U5 X
more: false }
其中“max_ram_size“字段的数据就是全网RAM的数量,单位是bytes,那么转换为G,则结果为:88402589696/(1024*1024*1024)=82.34263134002686 G。获取方式如下:
eos.getTableRows(true,"eosio","eosio","global").then(result => {* K' D: E" q' x+ Q2 e& U0 h8 F
//ram总量,bytes转为G
let ramTotal = result.rows[0].max_ram_size / (1024*1024*1024) / y! H3 x+ q+ y! b7 E& u
})
二、获取RAM使用量、计算RAM价格
与获取RAM总量一样,我们使用eosjs库的getTableRows方法获取主网中RAM的使用量、消耗RAM的EOS数量,最后通过Bancor算法计算RAM价格。! \: X S9 c2 F2 N# f- C4 E4 ?. U" _
eosconfig = {
httpEndpoint: 'https://node1.zbeos.com',
chainId: 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906', m( s) I) ]3 `: T% v2 y1 E
// keyProvider: privatekeyList, // WIF string or array of keys..1 X' g C- R0 ?$ U! ~% j
expireInSeconds: 60,
broadcast: true,
verbose: false, // API activity4 ~6 V, A& |4 x- J& I+ b' \1 A
sign: true
},7 K9 a% \3 t/ x" Q$ Z, Y4 b
eos = Eos(eosconfig)
eos.getTableRows(true, "eosio", "eosio", "rammarket").then(ramData => {( l7 H* | L; \" z5 ]
console.log(ramData) h/ F; f8 @# h, ^
})( _3 l( J7 ~% Y6 ~: z: Z
输出如下
其中“base“字段里的“balance”数据就是全网RAM的使用量,单位是bytes。
“quote“字段里的“balance”数据就是消耗RAM的EOS数量。3 t, ]6 a% Z3 _. ~
下面根据Bancor算法算出RAM的价格
ramPrice = quote.balance / (base.balance / 1024)) I& m# s/ Z3 M. u1 W- `* {, S6 A5 h
Bancor协议是底层货币协议,通过区块链技术和智能合约为加密数字货币提供连续流动性和实现异步价格。% M! c5 L, M6 H3 j/ o
所以ramPrice的获取方式如下:( c, w8 ]" q& B& q8 y
eos.getTableRows(true, "eosio", "eosio", "rammarket").then(ramData => {
console.log(ramData)# H9 L/ |9 s1 J L) u
//RAM消耗的EOS数量
let eosAmount = ramData.rows[0].quote.balance.split(" ")[0];& h+ A$ O5 V" |4 }% A J, @& [
//RAM使用量0 D% y8 {- S! _
let ramAmount = ramData.rows[0].base.balance.split(" ")[0] / 1024;
//RAM价格
let ramPriceWithEOS = eosAmount / ramAmount1 P9 h: W# A' H
console.log(eosAmount, ramAmount, ramPriceWithEOS);
})
三、买入RAM
买入RAM的API其实我们已经使用过了,在创建账号的时候我们为别人创建的账号就需要为它购买一定的RAM,现在我们在来单独调用购买的API。由于现在需要交易,所以会使用资源,因此我们重新配置一下eosconfig切换到测试网络进行测试。
eosconfig = {
httpEndpoint:"http://jungle.cryptolions.io:18888",
chainId: "038f4b0fc8ff18a4f0842a8f0564611f6e96e8535901dd45e43ac8691a1c4dca", // 32 byte (64 char) hex string8 l. L( B( Q# {, O( O
keyProvider: ["5HqCj7sg4K2xZ1KD5sSH38kuJkKGqfE1wSGiLL3M599ajacVmTs"], * W7 ^, B1 i! `2 Y- o, w/ T
expireInSeconds: 60,, v( M# r3 \- m. W. n! S
broadcast: true,
verbose: false, // API activity( Y+ d6 n* \/ L# ?
sign: true/ K& V! a3 p# T+ c/ h
}, f$ {; B+ D/ i6 C4 g& b, `; p, K; p
eos = Eos(eosconfig)( p; m( p& {- [3 s S+ U# E0 E
eos.getTableRows(true, "eosio", "eosio", "rammarket").then(ramData => {: K% X% U$ k v; P
console.log(ramData)9 O; t: A6 }2 `3 h
//RAM消耗的EOS数量
let eosAmount = ramData.rows[0].quote.balance.split(" ")[0];: R* W! s! @; {. E
//RAM使用量2 m& D' {0 p1 F/ |& F) J$ e1 }' J% @
let ramAmount = ramData.rows[0].base.balance.split(" ")[0] / 1024;
//RAM价格- n1 n- p/ N+ u% t
let ramPriceWithEOS = eosAmount / ramAmount
console.log(eosAmount, ramAmount, ramPriceWithEOS); |6 \6 l, B# S* x4 @
})
let account = "lixutest1111"
let ramAmount = 8*1024% O9 Y3 [5 G) |* d7 ]+ j1 W
async function buyRAM() {3 p& S) @1 @9 i& N( n( Q
result = await eos.transaction(tr => {3 |5 Z; s5 ^5 ~$ w3 O9 @
tr.buyrambytes({
payer: account,
receiver: account,8 R: Y& F1 |5 p9 C6 }) n9 }
bytes: ramAmount" _, I* z+ [9 p0 e6 q
})$ _) j3 U( O Q, [6 M
})
console.log(result)4 e" _* ^$ F1 J9 F8 U, {/ F
}
buyRAM()
在运行之前先记录下来账号“lixutest1111”的网络资源数据。
运行后看到价格是0.07576784159120188 EOS/KB
2 k Y: }( B7 _6 m- {9 R
代码中是买了8KB的RAM,那我们计算一下,需要花费多少EOS,其实很简单
8KB * 0.07576784159120188 EOS/KB = 0.6061EOS
那我们再计算一下账号“lixutest1111”现在的EOS可用余额和RAM总量是多少
78.7959 - 0.6061 = 78.1898EOS5 A% z9 K: u! w, ~
13.30 + 8 = 21.30KB
计算好以后我们再看看现在账号“lixutest1111”的在链上的资源数据是多少。
可以发现计算的结果和链上的结果有了一定的偏差,这是因为RAM价格会随着市场波动而变化,所以导致结果有一点点偏差,这是不可避免的。另外我们在购买RAM的时候,需要输入的是EOS数量,然后根据RAM价格转换成需要购买的RAM大小,再进行交易。7 m1 }, l) e5 q) A. X0 z
四、卖出RAM
卖出RAM需要用到另外一个方法 sellram
eosconfig = {
httpEndpoint: "http://jungle.cryptolions.io:18888",
chainId: "038f4b0fc8ff18a4f0842a8f0564611f6e96e8535901dd45e43ac8691a1c4dca", // 32 byte (64 char) hex string( `* e" s. x% a5 @
keyProvider: ["5HqCj7sg4K2xZ1KD5sSH38kuJkKGqfE1wSGiLL3M599ajacVmTs"],$ Q7 | p- U. K J
expireInSeconds: 60,
broadcast: true,3 j) o* C, t- K: o% k
verbose: false, // API activity- d/ u, z! t, A" ^1 F4 E
sign: true" M, B+ H6 ?, z) K' ~/ s
},
eos = Eos(eosconfig)
eos.getTableRows(true, "eosio", "eosio", "rammarket").then(ramData => {# d: L9 @5 c n( g1 V
console.log(ramData)# q( l! h N5 G
//RAM消耗的EOS数量
let eosAmount = ramData.rows[0].quote.balance.split(" ")[0];' ~* x7 ^' ?7 w/ e" e0 _1 u" i
//RAM使用量
let ramAmount = ramData.rows[0].base.balance.split(" ")[0] / 1024;
//RAM价格
let ramPriceWithEOS = eosAmount / ramAmount
console.log(eosAmount, ramAmount, ramPriceWithEOS);
})) `: ^0 i) q+ x+ `* D! f
let account = "lixutest1111"- ~1 E% u/ Q9 f
let ramAmount = 8*1024
async function sellRAM() {
result = await eos.transaction(tr => {
tr.sellram({0 s L9 b/ ^3 l! V- `/ v
account: account,3 @0 E; h3 ?* b1 v/ m% J( Y
bytes: ramAmount
})
})
console.log(result)
}
sellRAM()
运行后看到价格是0.0757692783033557 EOS/KB,确实与上一次获取到的价格有点偏差。
" H' g. g& k( y# y
这里就不花时间作计算了,大家可以在根据价格与出售量计算在做比较。重新查看账号“lixutest1111”的EOS数量多了0.6,RAM内存减少了8KB。
。9 {5 n% Y+ U$ d/ f4 K
五、项目源码# S2 z% T- b, i5 I2 y1 M z, k
1. controllers/netResource.js
在controllers文件夹下新建netResource.js文件,实现获取全局RAM数据与买入卖出RAM的功能。- w! m, w3 O; V. g
let { success, fail } = require("../utils/myUtils"). S" s& G( s1 e4 d
let myUtils = require("../utils/myUtils")
let walletModel = require("../models/wallet")
async function getRamInfo() {/ _% I+ T1 `- Z# N& y6 w% u6 H' x% T# ?
ramData = await eos.getTableRows(true, "eosio", "eosio", "rammarket")
//RAM消耗的EOS数量. ?8 [) P' b' t( t u3 a
let eosAmount = ramData.rows[0].quote.balance.split(" ")[0];
//RAM使用量! Z% P _& ]- g
let ramAmount = ramData.rows[0].base.balance.split(" ")[0] / 1024;
//RAM价格) T% t+ W: a- V7 p7 r5 l* L
let ramPriceWithEOS = eosAmount / ramAmount+ O2 z9 `: H" y) @
console.log(eosAmount, ramAmount, ramPriceWithEOS);( B- R% u, E8 \& X
return {
ramUsed: ramAmount / (1024 * 1024),
ramPrice: ramPriceWithEOS,
}
}: \8 v, b% U) p" t6 D5 J
module.exports = {
netResourceGetRAMInfo: async (ctx) => {
console.log(ctx.request.body)0 K2 q- n1 K- Y" L! ^/ q
let { wallet, password } = ctx.request.body
//获取钱包里面所有的私钥配置EOSJS( E$ i2 C& [ E$ ~- [9 V& t7 y
let privatekeyList = await walletModel.getWalletPrivatekeyList(wallet, password)
eos = myUtils.getEOSJS(privatekeyList)
let ramData = await eos.getTableRows(true, "eosio", "eosio", "global")
//ram总量,bytes转为G
let ramTotal = ramData.rows[0].max_ram_size / (1024 * 1024 * 1024): b+ s- J: @1 T7 r# @& A5 {
console.log(ramTotal);1 V$ D2 n0 B& F1 u9 L
let ramInfo = await getRamInfo()3 a$ [# P! Z2 u' ^. Y; k
ctx.body = success({
ramPrice: ramInfo.ramPrice,
ramTotal: ramTotal,' g, w- N; ^' N+ h
ramAvailable: ramTotal - ramInfo.ramUsed,% o; a; A) q6 I
})
},5 X# E& h3 x" O
netResourceTransactionRAM: async (ctx) => {. C" h, g% }. P% R# W& g( h
console.log(ctx.request.body)
let { amount, transaction_type, account, wallet, password } = ctx.request.body, Y2 b' g% v% `1 D! |2 g+ T X
//获取钱包里面所有的私钥配置EOSJS, b' A, o0 q* F7 G3 p5 o# P$ y
let privatekeyList = await walletModel.getWalletPrivatekeyList(wallet, password)
eos = myUtils.getEOSJS(privatekeyList)* m4 z2 L. ?+ `3 r* [! \9 B
let result8 u: @9 L) m) Q" ^3 F/ ?9 J
if (transaction_type == '1') {/ W) |$ c2 S. M5 x8 v- G0 h
//买RAM3 C' y# P. |. O- B
console.log("买RAM")# z# n- i* ?, m# t: }' a! I' d
let ramInfo = await getRamInfo()
let ramAmount = parseInt((amount / ramInfo.ramPrice) * 1024)/ Q7 I1 C, r: ^) @
console.log("ramAmount:", ramAmount)8 [1 T+ G% z [
result = await eos.transaction(tr => {. G7 b1 O; s3 _8 @
tr.buyrambytes({
payer: account,
receiver: account,! X/ @/ |2 H( p; b% M/ y! x
bytes: ramAmount+ B8 L+ u% l- y7 K4 d' r4 ?
})
})$ e, L0 X" r0 B
} else { B8 W3 l; Q" A" R: E7 d" d
//卖RAM
console.log("卖RAM")
let ramAmount = parseInt(amount*1024)7 T8 w) \6 c( K8 T
result = await eos.transaction(tr => { Q+ `/ j0 s& @* N
tr.sellram({
account: account,: b3 Q/ {1 C4 g/ i
bytes: ramAmount 0 k5 {2 a: \9 {/ k
})
})
}4 X) A4 \2 n9 Y1 b' b5 F4 l
console.log("data:", result)
if (result.broadcast) {+ c( I% S3 a# d! a/ e
ctx.body = success("ok")2 u( \6 @9 _+ r8 j+ Z: @' F
} else {
ctx.body = fail("error")
}, g! L% @$ {7 g; m% l
}# p$ i; s& d/ y6 @
}
2. router/router.js
将获取全局RAM数据与买入卖出RAM的接口绑定到路由。$ u4 F) ~& L) c3 J! p
......, N! a1 J% l4 | s4 V+ [# D
let netresourceController = require("../controllers/netResource")
//网络资源9 W: |; M% m" t& k1 @6 D
router.post("/net_resource/ram/info", netresourceController.netResourceGetRAMInfo)( C/ B4 Z* Z- V# Q/ b! Y0 n8 C
router.post("/net_resource/ram/transaction", netresourceController.netResourceTransactionRAM)
3. views/netResource.html
编辑views文件夹下的netResource.html文件,实现RAM交易的表单显示。 O; o- v! r7 r) a7 K( D
...... Q9 y0 }- R; p, c: P& Z% [
8 _8 ^, {. f+ B
买入
: f M5 G0 z- h3 q& L! h" ~9 X8 h
卖出
全网内存:
内存价格: EOS/KB
数量:
4 f6 u& P% H0 k) K+ w. L
买入
3 X; U- m3 r- A: n3 B. n2 Z- N. ]
......+ g3 c7 }) i/ i+ C
4. static/js/netResource.js7 _1 `5 C/ |: p! I. u7 B2 E2 H* S
对全局RAM数据与买入卖出RAM的表单进行网络请求处理与页面渲染。
$(document).ready(function () {
......
$("input[name=account][hidden=hidden]").val(currentAccount)
let currentwallet = localStorage.getItem("currentwallet")9 o' f' V, t( P8 @
let walletPassword = localStorage.getItem(currentwallet)
$("input[name=wallet][hidden=hidden]").val(currentwallet); ]! K% j2 n' `9 d, o$ S* _
$("input[name=password][hidden=hidden]").val(walletPassword): B# ^7 c |3 d+ _
$("input[name=transaction_type]").change(function () {" h: \3 ]. H* `2 a
if (this.value == 1) {( H3 s: A9 N0 L Z, v* \- D
$("#ram-transaction-button").text("买入") X. b! y+ n, c) m9 b: o0 c
$("input[name=amount]").attr({"placeholder":"请输入EOS数量"})' R' z, N+ {, `6 P4 e
} else {
$("#ram-transaction-button").text("卖出")
$("input[name=amount]").attr({"placeholder":"请输入RAM(KB)数量"})
}
})) N5 f) I8 }# I
//ram全局数据# d `) e% [. a! b8 s: |' _+ ]( E
$.post("/net_resource/ram/info", { "account": currentAccount }, function (res, status) {
console.log(status + JSON.stringify(res))( n7 I: t/ \# H0 C: j" n
if (res.code == 0) {6 R8 R! R3 \/ j( Z3 _
$("#ram-total").text(res.data.ramAvailable.toFixed(2) + " GB / " + res.data.ramTotal.toFixed(2) + "GB")
$("#ram-price").text(res.data.ramPrice.toFixed(6))$ U; g, h; A8 \( B# F4 f9 }' U, f
}
})
//交易RAM
$("#ram-transaction").validate({
rules: {" B( y9 ~& @1 ] R F7 Y) d, D
amount: {required: true,},
},
messages: {& C! ?4 H, g3 Y Q8 _: C# {' P
name: {required: "请输入要交易的数量",},. U3 n3 E2 z D0 }5 A( n1 s
},
submitHandler: function (form) {. X( i1 n- u' T- |7 q j/ {7 W- n
$(form).ajaxSubmit({% V) H8 x8 ?& u" B/ Q6 s2 B
url: "/net_resource/ram/transaction",
type: "post",
dataType: "json",
success: function (res, status) {$ x. |7 R" j0 w& M
console.log(status + JSON.stringify(res))
if (res.code == 0) {% X% j# Z' Z: ^+ N5 @7 H# Z
alert("交易成功")
location.reload()
} else {$ p4 A$ I6 e# j+ l5 G H* K6 w" y
alert("交易失败")
}7 n$ {1 V4 p; g# a
},
error: function (res, status) {
console.log(status + JSON.stringify(res))- T: y, T0 Z5 z' Z1 K. v
alert(res.data)" S1 P, B5 a+ F: F# v
}0 R% f: e3 K F' I9 l/ D( g; o
});) Q9 m* \/ b5 _% J
}
})
})9 \* |! W8 A; Z, Y/ R1 ]8 i
# p. b6 y7 [& v) W7 e& t7 o( c
成为第一个吐槽的人