0

I am building an exchange where you can buy and sell tokens.

I have a contract Exchange. It contains a function sellTokens which will take the amount of tokens entered by a user and give them a corresponding amount of ether.

However, when the contract is initiated, it will always have a balance of 0 ether until buyTokens function is executed and the contract is funded with some ethereum.

Question: What is the best way to fund this contract on creation? Does this have to be done manually after the contract has been deployed or is it possible to automate this in the constructor?

Please let me know if I can provide any more information.

2 Answers 2

0

You can automate this process adding payable keyword to constructor and implement. So, when you deploy smart contract you funds it with some ether from your balance. However, I suggest you to implement a function whenever you want to funds in a particular situation your smart contract accessible only to smart contract owner.

You can see an example of smart contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FundsSmartContract {
    address owner;

    constructor() payable {
        owner = msg.sender;
        // your logic
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "You aren't smart contract owner!");
        _;
    }

    // Check address about smart contract
    function funds(uint _amount) public payable onlyOwner {
        // your logic
    }

    // Check address about smart contract
    function getBalanceSmartContract() external view returns(uint) {
        return address(this).balance;
    }
}

NOTE: If you're using Remix IDE to test it, remember to set into VALUE textbox the amount of ether when you'll call payable functions.

0

Other than making a constructor payable. You can also add the receive function which would allow you to fund the contract at a later stage, and could also save you from many security vulnerabilities if used right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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