Solidity
使用介面從其他智能合約購買代幣
我有兩個單獨的契約,比如說
Token
和BuyFrom
。pragma solidity >=0.4.22 <0.7.0; interface InterfaceToken { function invest(address contributor) external payable; } contract Token { string public name = "Token"; string public symbol = "TKN"; uint public decimals = 0; uint tokenPrice = 1000000000000000; uint public supply; address public founder; address payable public deposit; mapping(address => uint) public balances; constructor(address payable _deposit, address _founder) public{ supply = 300000; deposit = _deposit; founder = _founder; balances[founder] = supply; } function invest(address contributor) public payable { uint tokens = msg.value / tokenPrice; balances[contributor] += tokens; balances[founder] -= tokens; deposit.transfer(msg.value); } }
我想
BuyFrom
使用界面購買代幣。但它不起作用。pragma solidity >=0.4.22 <0.7.0; import 'Token.sol'; contract BuyFrom { address payable private token; constructor(address payable _token) public { token = _token; } function buyToken(address contributor) external payable { InterfaceToken(token).invest(contributor); } }
我做錯了什麼?
由於
InterfaceToken(token).invest
是外部呼叫(即,對另一個合約中的函式),您需要傳遞您的函式收到的值。換句話說,改變這個:
InterfaceToken(token).invest(contributor);
對此:
InterfaceToken(token).invest.value(msg.value)(contributor);