我正在写一份智能合同,其中将包含一个托管服务。托管将是一个智能契约,最终我希望使用它将元令牌从escrows地址传输到另一个用户。我的问题是,我希望能够转移从托管,但有一个修饰符,只允许托管合同本身调用。我试着做一个修饰符,它只允许"this“(指合同地址)打电话,但不起作用。
如果一个合同内部调用了另一个函数,我如何才能拥有它,即只有合同本身才能调用该函数并发生转移。Msg.sender似乎不能适应这种情况。
我的守则:
modifier contractOnly(){
address contractAddress = this;
if(msg.sender != contractAddress) throw; _
}以及传输函数(它需要修饰符来阻止任何人调用该函数并从托管行获取所有令牌)
function transfer(address from, address to, uint amount)
contractOnly returns (uint) {
balances[from] -= amount;
balances[to] += amount;
return balances[from];
}发布于 2016-08-23 19:12:39
您应该能够使用internal修饰符这样编写您的函数,该修饰符是内置于solidity中的。
function transfer(address from, address to, uint amount) internal returns (uint) {
balances[from] -= amount;
balances[to] += amount;
return balances[from];
}这意味着transfer函数只能从本合同中其他函数的函数体中调用。相反,transfer函数将不能从任何其他契约中调用。
如果契约实际调用自己(而不仅仅是内部调用函数),您提供的修饰符就会起作用。
contract MyInterface {
modifier contractOnly(){
address contractAddress = this;
if(msg.sender != contractAddress) throw; _
}
function transfer(address from, address to, uint amount) contractOnly returns (uint);
}
contract TheContract is MyInterface {
function transfer(address from, address to, uint amount) contractOnly returns (uint) {
...
}
function thisWillWork(address from, address to, uint amount) {
MyInterface(address(this)).transfer(from, to, amount);
}
function thisWillFail(address from, address to, uint amount) {
transfer(from, to, amount);
}
}在本例中,thisWillWork函数将transfer函数作为内部事务调用,这意味着两个契约之间的事务。事实证明,它只是在与自己打交道,但它是作为一个外部召唤来进行的。在这种情况下,msg.sender值变为address(this),因为调用发生在由契约本身发起的事务中。
thisWillFail函数使用内部调用样式,这意味着它不生成内部事务,而是使用一个JUMPDEST调用当前正在运行的事务中的transfer函数的代码。在这种情况下,msg.sender值被保留为原始调用者,因为调用不是发生在新事务中,而是在当前事务的上下文中。
https://ethereum.stackexchange.com/questions/7814
复制相似问题