以问题的形式来记录
-
为什么可以在浏览器和钱包里面和波场链交互? 因为TronLink 会将tronWeb及tronLink对象注入每个浏览器页面 参考链接:Dapp集成Tronlink介绍 -
js如何获取tronWeb对象
let tronWeb = window.tronWeb
- 如何和合约交互(创建包装ABI的合约对象。 使您可以轻松地调用合约中的函数)
(1)创建合约实例
let abi = [...];
let instance = await tronWeb.contract(abi,'contractAddress');
let instance = await tronWeb.contract.at('contractAddress');
(2)调用合约的函数(查询信息-call,操作合约-send,监听-watch)
let res = await instance.totalSupply().call({_isConstant:true})
参考:链接合约 调用合约方法
- 如何获取钱包地址和余额
address = window.tronWeb.defaultAddress.base58
let trxbalance = await tronWeb.trx.getBalance(address);
let contract = await tronWeb.contract().at(trc20ContractAddress);
let mybalance = balance.toNumber();
附一个小demo,转账部分介绍链接
function paying(){
var selval = 2;
var data_contract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
var paynum = $("#paynum").val();
if(!paynum||paynum==''||paynum==null){
alert('请输入充币数量');
return;
}
if(paynum<=0.01){
alert('充币数量不得小于0.01个');
return;
}
var TRX_IN_ADDR = '{$TRON_COLLECT_ADDR}';
if(selval==2){
transfer1(TRX_IN_ADDR,paynum);
}else{
transfer2(TRX_IN_ADDR,paynum,data_contract);
}
}
async function transfer2(addr_to,pay_num,token_addr){
var pay_num_wei = parseInt(pay_num * 1000000);
const trc20ContractAddress = token_addr;
var address_to = addr_to;
let myaddress = window.tronWeb.defaultAddress.base58;
try {
loading();
let contract = await tronWeb.contract().at(trc20ContractAddress);
let balance = await contract.balanceOf(myaddress).call();
let mybalance = balance.toNumber();
let trxbalance = await tronWeb.trx.getBalance(myaddress);
if(mybalance<pay_num_wei){
loaded();
alert('账户余额不足');return;
}
let feeLimit = 10000000;
if(trxbalance<feeLimit){
loaded();
alert('账户能量不足10trx');return;
}
let result = await contract.transfer(
address_to,
pay_num_wei
).send({
feeLimit: feeLimit
(1TRX = 1,000,000SUN)
}).then(output => {
loaded();
msg_alert('交易广播成功');
});
} catch(error) {
loaded();
msg_alert('操作取消');
}
}
async function transfer1(addr_to,pay_num){
let tronWeb = window.tronWeb;
let myaddress = window.tronWeb.defaultAddress.base58;
var pay_num_wei = parseInt(pay_num * 1000000);
let trxbalance = await tronWeb.trx.getBalance(myaddress);
if(pay_num_wei>trxbalance){
msg_alert('账户余额不足');return;
}
loading();
await tronWeb.trx.sendTransaction(addr_to,pay_num_wei).then(result => {
if (result.result) {
loaded();
msg_alert('交易广播成功');
} else {
loaded();
msg_alert("操作取消1");
}
}, err=> {
loaded();
msg_alert("操作取消2");
});
}
|