0

Hello I'm just making an easy smart contract. By reading it you should understand it.

contract Idk {
    Thing[] deployedThings;

    function createSomething(address  _name) public {
        Thing newThing=new Thing(_name);
        deployedThings.push(newThing);
    }

    function seeThings() public view returns(Thing[] memory){
        return deployedThings;
    }

}

contract Thing {
    
    address name;
    constructor(address _name ) {
        name= _name;  
    }

    function sendEth() public payable {
        require(msg.value==1 ether);
        payable(name).send(0.2 ether);
    }
 }

So the problem is that when i send 0.2 to the address the rest of ether goes to the Thing smart contract but i would like to send the rest of the ether to the Idk contract. Is it possible to make it?

1 Answer 1

1

Here's how you can do it.

  1. You'll have to bind the parent address (IDK) to the child contract (Thing), so it can send funds back to it. See createSomething() where we send address(this) when we create a new item.
  2. Thing will save this second argument as the parent.
  3. In the sendEth() method, we'll split 0.2 to the name (I suggest picking a more intuitive variable name here) and 0.8 to the parent. We make sure to check the transfer statuses so they don't fail.
  4. We have to instruct IDK to receive funds, using the receive() fallback method.

Note: for transferring tokens, we'll use the call format. More on this here.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract Idk {
    Thing[] deployedThings;

    function createSomething(address  _name) public returns (address) {
        Thing newThing= new Thing(_name, address(this));
        deployedThings.push(newThing);
        return address(newThing);
    }

    function seeThings() public view returns(Thing[] memory){
        return deployedThings;
    }

    // instruct the contract to accept ETH or it will revert without it

    receive() payable external {}     
 }


contract Thing {

     address public name;
     address public parent;

    constructor(address _name, address _parent) {
        name= _name;
        parent = _parent; // bind the factory/parent address
    }

    function sendEth() public payable {
        require(msg.value==1 ether, "Value has to be 1 ether");

        (bool success1, ) = name.call{value: 0.2 ether}("");
        require(success1, "First transfer failed");
        
        (bool success2, ) = parent.call{value: 0.8 ether}("");
        require(success2, "First transfer failed");
    }
}
1
  • Thank you !!!!!!
    – arzr
    Jan 15 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.