What is the use of Uniswap Router Initialization in a Token Contract

Viewed 2721

I just started on building Tokens using ETH & BSC, this is one statement which I see in many Contracts. Inside the Constructor method, the Uniswap router is iniliazed probably with the V2 version. What is the use of this?

 constructor () public {
 _rOwned[_msgSender()] = _rTotal;
        
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
         // Create a uniswap pair for this new token
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
            .createPair(address(this), _uniswapV2Router.WETH());

        // set the rest of the contract variables
        uniswapV2Router = _uniswapV2Router;
        

Why is this initialization required? What is the functionality of this?

Appreciate if someone could help.

Thanks

1 Answers
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);

This line initializes a pointer to the 0x10ED... address and expects the contract (deployed at the 0x10ED... address) to implement the IUniswapV2Router02 interface.

The interface is defined somewhere with the caller contract source code.

It allows you to execute and call functions defined by the interface instead of building low-level calls. It also allows you to use the returned datatypes instead of parsing the returned binary.

Example:

pragma solidity ^0.8.5;

interface IRemote {
    function foo() external view returns (bool);
}

contract MyContract {
    IRemote remote;

    constructor() {
        remote = IRemote(address(0x123));
    }

    function getFoo() external view returns (bool) {
        bool returnedValue = remote.foo();
        return returnedValue;
    }
}
Related