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