How to access the library from Blockchain inside the smart contract?

Libraries

Libraries in Solidity smart contracts are blocks of reusable code. Libraries also help you to save gas by using the existing code that is already available on the Blockchain instead of writing the code again. 

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

library ArrayLib {
    function find(uint[] storage arr, uint x) external view returns(uint i) {
        for (i; i <= arr.length; i++) {
            if (arr[i] == x) {
                return i;
            }

        }
    }

    function insert(uint[] storage arr, uint num) external returns(uint[] memory){
        arr.push(num);
        return arr;
    }
}

contract CodiesAlert {
    uint[] public arr = [1,2,3,4];

    function getIndex() public view returns(uint) {
        return ArrayLib.find(arr, 4);
    }

    function insertNum() public returns(uint[] memory) {
        return ArrayLib.insert(arr, 4);
    }

    function returnUpdatedArray() public view returns(uint[] memory) {
        return arr;
    }

    function returnLibAddr() public view returns(address) {
        return address(ArrayLib);
    }

     function returnContractAddr() public view returns(address) {
        return address(this);
    }
}

				
			

Deploy Fresh library with the contract

If you will deploy the above contract CodiesAlert in REMIX IDE it will first deploy the library and then automatically links the library address with the contract and deploy it on Blockchain.

REMIX IDE takes care of it because of the settings in the codiesalert.json file where autoDeployLib is true. Your library address will be automatically replaced in ArrayLib. REMIX takes care of everything under the hood.

How to use an existing library that is already deployed on the Blockchain?

 

  1. Select ArrayLib library and deploy it on Blockchain and now we have the address of the library where it is deployed on the Blockchain.
 
  2. In the next step, copy the address of the library that you have deployed in the previous step. Goto Contract -> artifacts and click on codiesalert.json file. Change autoDeployLib to false and update the address in front of ArrayLib. 

3. Now, you are ready to deploy the contract that will use the existing library from the Blockchain. As you can see in the below screenshot when you click on the returnLibAddr function, it is returning the same address that we had updated in the previous step.
 
NOTE: We still need the library source code in the contract even though we are using the existing library but this will save us gas and it won’t deploy the library source on the Blockchain. 
 

Leave a Reply

https://www.linkedin.com/company/77619036/admin/

welcome.

We connect you to a world of houseplants and urban gardening tailored to your home

Bloomer

Login to your account