enviar ethers de un contrato a otro

Me pregunto cómo puedo tener éteres en mi contrato. Tengo 2 contratos asociados a diferentes cuentas.

Quiero enviar ethers de un contrato a otro, pero ¿cómo tengo primero ethers en mi contrato para poder enviarlo?

Aquí está el ejemplo:

contract ethertransfer {    
  function fundtransfer(address etherreceiver, uint256 amount) {
    if(!etherreceiver.send(amount)) {
       throw;
    }
  }
}

contract etherreceiver {

  function etherreceiver() {      
  }
}

Respuestas (6)

  1. Envíe Ether a su contrato ( ethertransfer) desde la cuenta externa (un término para cuentas controladas por el usuario). Para poder hacerlo, debe tener una payablefunción en su contrato (que podría ser la función alternativa https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function ). La función de pago es la función con el payablemodificador (por ejemplo, function receivePayment() payable {}). Luego, debe enviar la transacción (si se define la función de respaldo) al contrato o llamar a la función en su contrato (si decidió tener una para recibir pagos). Puede utilizar el cliente web3 para interactuar con su contacto.

  2. Es casi lo mismo cuando se envía Ether de un contrato a otro. El contrato de destino también debe tener una payablefunción (podría ser nuevamente: la función de respaldo o cualquier otra).

    • Si la función de reserva está definida: utilice etherreceiver.transfer(100)oetherreceiver.send(100)
    • Si hay una función personalizada definida, useetherreciver.myPayableFunction.value(100)(myArgument1, myArgument2)

Lecturas adicionales: recomiendo leer la sección al respecto modifiersque lo ayudará a comprender qué payablees: https://solidity.readthedocs.io/en/latest/contracts.html#function-modifiers

ACTUALIZACIÓN: en Solidity 0.6+, la sintaxis ha cambiado a: address.function{value:msg.value}(arg1, arg2, arg3)para la función personalizada de pago, llame a ethereum.stackexchange.com/questions/9705/…

El enfoque más simple es una payablefunción, luego envíele fondos desde una cuenta regular.

contract ethertransfer{

    function payMe() payable returns(bool success) {
        return true;
    }

    function fundtransfer(address etherreceiver, uint256 amount){
        if(!etherreceiver.send(amount)){
           throw;
        }    
    }
}


contract etherreceiver{       
    function etherreceiver(){          
    }    
}

Espero eso ayude.

Como se mencionó anteriormente, defina una función pagadera para recibir los fondos, por ejemplo:

function fund() payable returns(bool success) {
}

Luego llame a esta función y proporcione los éteres en el campo de valor.

Después de que el tx tenga éxito, defina una función en la que use send(), por ejemplo:

contract_destination_address.send(amount);

1) Envía Ether a tu contrato

 Step-1: Create a payable method in your contract just to receive some ether. 
         Better use empty payable fallback method(Can just use the contract address to send ether) 

Ex:

ingrese la descripción de la imagen aquí

 Step-2: Send the transaction to your contract using web3js.

2) Enviar Ether de un contrato a otro contrato

Esto se puede ilustrar mejor con un ejemplo.

**Ex:**

//Contrato para recibir Ether de otro Contrato

contrato TransferEtherTo{

function getBalance() returns(uint){
    return address(this).balance;
}

//Empty payable fallback method just to receive some
 function() payable{
}

}

//**************************************************** ************///

//Contrato para enviar Ether a otro Contrato

contrato TransferEtherFrom{

//Declaring an instance of TransferEtherTo contract
TransferEtherTo instance;

constructor(){
    //Initializing TransferEtherTo contract
    instance = new TransferEtherTo();
}

//Returns balance of TransferEtherFrom contract
function getBalance() returns(uint){
    return address(this).balance;
}

//Returns balance of TransferEtherTo contract
function getBalanceInstance() returns(uint){
    return instance.getBalance();
}
//Transfers ether to other contract
function transfer() payable{
    address(instance).send(msg.value);
}

//Fallback function to receive and transfer Ether
function() payable{
    address(instance).send(msg.value);
}

}

Todos los éteres enviados al contrato TransferEtherFrom (a través de métodos alternativos o transfer()) se enviarán al contrato TransferEtherTo .

el contrato del remitente

     contract theSender {

     /*Harcoding receiver contract address, one can also use contructor to assign 
      address */
     address payable theReceiverContractAddress;
     theReceiverContractAddress = '0x01...'

     //this is an empty function to receive ether from wallet accounts using web3
     function receiverether() external payable {}

     function balanceof() { 
      return address(this).balance;
      }

     /*this will tranfer the ether stored at this contract's address to the below 
     address */
     function debit() external{ theReceiverContractAddress.transfer(value);}

}

Ahora el contrato de recepción

contract theReceiver{

/*this is required to receive ether from any source, this will store received ether in 
this contract's address */ 

receive() external payable{}

}

Para esto, debe crear la función que está llamando a address.transferas payable. Además, también debe haber una función pagadera en el contrato de recepción.

contract ethertransfer {    
  function fundtransfer(address etherreceiver, uint256 amount) public payable {
    if(!etherreceiver.transfer(amount)) {
       throw;
    }
  }
}

contract etherreceiver {

  function etherreceiver() external payable{      
  }
}

Ahora, cuando llame a la función fundtransfer() , simplemente ingrese la dirección del contrato etherreceiver y la cantidad de ethers que desea transferir.

Después de eso, mientras llama a la función desde el lugar deseado (remix/web3js), simplemente ingrese el valor = no. de éteres , de esto se deducirá el no. de éteres de la cuenta que llama fundtransfer()y transfiera el value-amountnúmero de éteres al contrato del receptor de éter.