波场(Tron)开发指南

in #starnote5 years ago

波场开发的实践总结:基础工具的使用,和合约的交互方法,单位转换和监听事件等。
-> 前往星空笔记

Sort:  

Tron-Web:JavaScript接口,用于提供常用的账户,地址,转账,合约相关操作。相当于Ethereum的web3js。

tron-box:提供合约编译,部署,测试的命令行工具。作用相当于Ethereum的truffle工具链。

tronLink,tronPay: 提供浏览器环境的钱包插件,为dapp提供便利和安全的执行环境,相当于Ethereum的MetaMask,Scatter。

tron-grid:社区维护的主网和测试网HTTP API接口,相当于Ethereum社区中的Infura。

Tron-IDE: 一款帮助开发者开发智能合约的在线编辑器。它具有模块化的特点,以插件的方式为开发者提供智能合约的编辑,编译,部署,调试等功能。

cnpm install -g tronbox

tronbox -v

Usage: tronbox <command> [options]
Commands:
  init     Initialize new and empty tronBox project
  compile  Compile contract source files
  migrate  Run migrations to deploy contracts
  deploy   (alias for migrate)
  build    Execute build pipeline (if configuration present)
  test     Run JavaScript and Solidity tests
  console  Run a console with contract abstractions and commands available
  watch    Watch filesystem for changes and rebuild the project automatically
  serve    Serve the build directory on localhost and watch for changes
  unbox    Download a tronbox Box, a pre-built tronbox project
  version  Show version number and exit

tronbox compile 编译

//Shasta测试网
tronbox migrate --network Shasta  //布署上线
tronbox migrate --network Shasta  --reset
https://shasta.tronscan.org/#/  //区块浏览器

//主网
tronbox migrate --network Mainnet --reset
https://tronscan.org/#/   //区块浏览器

Running migration: 1_initial_migration.js
  Replacing TronSteem...
  TronSteem:
    (base58) TRMAPytzETkYRsr4ug5Fts66XvxyTed3SK
    (hex) 41a8b0dd11fab3737ba5be4f7f72a2a4363f98d5b4
Saving artifacts...

— API:
https://api.shasta.trongrid.io
https://api.trongrid.io/
module.exports = {
  networks: {
    Shasta: {
      from: 'TDEQDahvDBQiByPMWUK3gP4iKPQqywnVVk',
      privateKey: '188xxxxxx',
      consume_user_resource_percent: 30,
      fee_limit: 300000000,
      fullHost: "https://api.shasta.trongrid.io",
      // fullNode: "https://api.shasta.trongrid.io",
      solidityNode: "https://api.shasta.trongrid.io",
      eventServer:  "https://api.shasta.trongrid.io",
      network_id: "*" // Match any network id
    },

    Mainnet: {
      from: 'TDEQDahvDBQiByPMWUK3gP4iKPQqywnVVk',
      privateKey: 'eb3xxxxxxxx',
      consume_user_resource_percent: 30,
      fee_limit: 300000000,
      fullHost: "https://api.trongrid.io",
      solidityNode: "https://api.trongrid.io",
      eventServer:  "https://api.trongrid.io",
      network_id: "*" // Match any network id
    },

    Mainnet2: { //另一种写法
      from: 'TDEQDahvDBQiByPMWUK3gP4iKPQqywnVVk',
      privateKey: 'eb3xxxxxxx',
      userFeePercentage: 100,
      feeLimit: 3e8,
      fullHost: 'https://api.trongrid.io',
      network_id: '1'
    },
},

compilers: {
    solc: {
      version: '0.5.8'
    }
  },
};

货币
类似于solidity对ether的支持,波场虚拟机的代码支持的货币单位有trx和sun,其中1trx = 1000000 sun,大小写敏感,只支持小写。目前Tron-IDE支持trx和sun,在remix中,不支持trx和sun,如果使用ether、finney等单位时,注意换算(可能会发生溢出错误)。 我们推荐使用Tron-IDE代替remix进行tron智能合约的编写。

区块相关
block.blockhash(uint blockNumber) returns (bytes32):指定区块的区块哈希——仅可用于最新的 256 个区块且不包括当前区块;而 blocks 从 0.4.22 版本开始已经不推荐使用,由 blockhash(uint blockNumber) 代替
block.coinbase (address): 产当前区块的超级节点地址
block.difficulty (uint): 当前区块难度,波场不推荐使用,设置恒为0
block.gaslimit (uint): 当前区块 gas 限额,波场暂时不支持使用, 暂时设置为0
block.number (uint): 当前区块号
block.timestamp (uint): 当前区块以秒计的时间戳
gasleft() returns (uint256):剩余的 gas
msg.data (bytes): 完整的 calldata
msg.gas (uint): 剩余 gas - 自 0.4.21 版本开始已经不推荐使用,由 gesleft() 代替
msg.sender (address): 消息发送者(当前调用)
msg.sig (bytes4): calldata 的前 4 字节(也就是函数标识符)
msg.value (uint): 随消息发送的 sun 的数量
now (uint): 目前区块时间戳(block.timestamp)
tx.gasprice (uint): 交易的 gas 价格,波场不推荐使用,设置值恒为0
tx.origin (address): 交易发起者

cnpm install tronweb --save

注意: window.tronWeb 是页面中最后加载的!

mounted() {
  let that = this
  async function main(){
    await that.sleep()  //等待6秒
    //tronlink
    if (window.tronWeb) {
      // console.log(22, "tronlink is ok! login")
      that.addr = window.tronWeb.defaultAddress.base58
    }else{
      that.tronlinkFlag = false
    }
    that.isLoading = false
    that.loadingFlag = true

    //如果没有获取到则再获取一次
    if(!that.tronlinkFlag){
      that.isLoading = true
      await that.sleep()
      //tronlink
      if (window.tronWeb) {
        console.log(522, "tronlink is ok! login")
        that.addr = window.tronWeb.defaultAddress.base58
      }else{
        let link2 = 'TronLink: https://www.tronlink.org'
        that.showMask = true
        that.maskInfo = "出错啦!请安装TronLink!\n"+link2
        that.tronErrorFlag = true
        that.isLoading = false
      }
    }
    that.isLoading = false
    that.loadingFlag = true
  }
  main()
}
async transfer(){
  console.log(161222, "Yes, catch it:", window.tronWeb)
  let tronweb = window.tronWeb
  let sendTransaction = await tronweb.trx.sendTransaction("TVJ1Waucj32mSMuFRab7kn73Pm6KyZGBmg", 1000)
  console.log(566, sendTransaction)
}
let res = await that.axios.get('/Test.json')
// console.log(66744, res)
let data = res.data
let tronWeb = window.tronWeb
let address = tronWeb.address.fromHex(data.networks['*'].address)  //转变成base58
let contract = tronWeb.contract(data.abi, address)
let s = await contract.a().call() //查询方法view
let stringx = 'WSTEEM是ERC20代币,旨在打通STEEM和以太坊网络的通道,使资产自由流通!'
let s2 = await contract.set(stringx).send() //更改方法

波场中得到的uint数据都是16进制(hex,如:[{"_hex":"0x0f4240"}]),如果在js中做加减乘除可以自动转换成10进制,也可以自动调整。
1 trx = 1000000 sun

uint public b = 1 trx;

let  b = await contract.b().call() //查询方法view
console.log(333, 'b', tronWeb.toBigNumber(b).toFixed())
//333 "b" "1000000"

tronWeb.fromSun()
> tronWeb.fromSun("1000000")
'1'
本地创建的得到 object
浏览器创建的得到 string

tronWeb.toSun()
tronWeb.toSun(10)
>"10000000"

用公钥P作为输入,计算SHA3得到结果H, 这里公钥长度为64字节,SHA3选用Keccak256。
取H的最后20字节,在前面填充一个字节0x41得到address。

对address进行basecheck计算得到最终地址,所有地址的第一个字符为T。

其中basecheck的计算过程为:首先对address计算sha256得到h1,再对h1计算sha256得到h2,取其前4字节作为check填充到address之后得到address||check,对其进行base58编码得到最终结果。

我们用的字符映射表为:
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

在波场中地址格式为:"TPY1jv2wrnEHpQAxfQ7BbpyKsDQRZTYDPX"
16进制表示:"4194cdf62db7f02319ec3b9a4009ba60854a896072"
转换函数:tronWeb.address.fromHex(address) //16进制转base58
this.tronWeb.address.toHex(dd) //base58转16进制
eg:
NutboxsPeanuts:
(base58) TYuDs3D3RZVXKhfPocYSyDBV8rES3MEiSs
(hex) 41fb89f2d17db9b45988645908a623855d956d5ba9

注意:波场区块链底层仍是使用的16进制的方式,但是与前端交互的却是使用的base58

New to Steemit?

Coin Marketplace

STEEM 0.08
TRX 0.29
JST 0.035
BTC 107514.50
ETH 3715.70
USDT 1.00
SBD 0.56