How to pledge bnb to the contract

In general smart contracts, the pledged currency is generally a token, which is very easy to handle. Occasionally, there will be a situation of pledging bnb, how to deal with this, let me give an example below.
function invest(address fromad,address irefer, uint256 amount) public payable { require(fromad==msg.sender); require(msg.value>=amount); //add amount must be 1, 2, 5 //… / / addrefer(fromad, irefer, amount.mul(15000).div(10)); addalluser(fromad); addmyson(fromad, irefer);







	users storage user = Users[fromad];
    user.amountbnb=user.amountbnb.add(amount);
    require(user.amountbnb+amount<=20*decimals,"must less than 20BNB");
	user.deposits.push(Deposit(block.timestamp,amount,amount.mul(15000)));
}
比如,正常的质押代币,用ERC20直接调用转帐就可以了,但是,如果是转bnb,ERC20就失效了。
首先对函数做一下介绍。
1、函数要写成payable类型的。
2.msg.value,是用户在调用invest方法的时候,向合约发了多少个bnb.
这两个是必须的。那么前端如何拉起小狐狸钱包,调用呢,可以用以下方式:
  let params=[
  {
    from: fromad,
    to: toad,
    gas: '0x9cc3e', // 30400
    gasPrice: '0x2540be400', // 10000000000000
    value: this.$web3.utils.toHex(val), // 2441406250
    data:
      '0x000000000000000000000000,
  },
];

Among them, the data is in front of the method, followed by the parameters to call the method, converted into hexadecimal, if not enough 64 bits, fill up the 64 bits
let res1=await ethereum
.request({ method: 'eth_sendTransaction', params, }) Supplementary explanation : value is the number of bnb transferred to the contract when calling the method, which is the value obtained by msg.value. data is the data formatted by the call method, as long as the data is added, the perfect call can be realized. It took me a lot of effort to toss for the first time, so I put it here to share with you. Friends who like to communicate, add V: 54516204, and communicate together.






Guess you like

Origin blog.csdn.net/weixin_38532278/article/details/125094935