Convert Figma logo to code with AI

smartcontractkit logochainlink

node of the decentralized oracle network, bridging on and off-chain computation

6,937
1,681
6,937
190

Top Related Projects

Go implementation of the Ethereum protocol

OpenZeppelin Contracts is a library for secure smart contract development.

14,020

:warning: The Truffle Suite is being sunset. For information on ongoing support, migration options and FAQs, visit the Consensys blog. Thank you for all the support over the years.

3,826

Security analysis tool for EVM bytecode. Supports smart contracts built for Ethereum, Hedera, Quorum, Vechain, Rootstock, Tron and other EVM-compatible blockchains.

4,956

A python interface for interacting with the Ethereum blockchain and ecosystem.

Aave Protocol Version 1.0 - Decentralized Lending Pools

Quick Overview

Chainlink is an open-source blockchain oracle network that enables smart contracts to securely access off-chain data feeds, web APIs, and traditional bank payments. It provides a decentralized network of nodes to deliver reliable tamper-proof inputs and outputs for complex smart contracts on any blockchain.

Pros

  • Decentralized and secure oracle network
  • Supports multiple blockchains and data sources
  • Widely adopted in the DeFi ecosystem
  • Robust documentation and developer resources

Cons

  • Complexity in implementation for some use cases
  • Reliance on LINK token for network operations
  • Potential centralization concerns with node operators
  • Higher costs compared to centralized alternatives

Code Examples

  1. Basic request for off-chain data:
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract PriceConsumerV3 is ChainlinkClient {
    using Chainlink for Chainlink.Request;
    
    uint256 public price;
    
    function requestPrice(address _oracle, string memory _jobId, uint256 _payment) public {
        Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), address(this), this.fulfill.selector);
        req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
        req.add("path", "USD");
        req.addInt("times", 100);
        sendChainlinkRequestTo(_oracle, req, _payment);
    }
    
    function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) {
        price = _price;
    }
}
  1. Using Chainlink VRF for random number generation:
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";

contract RandomNumberConsumer is VRFConsumerBase {
    bytes32 internal keyHash;
    uint256 internal fee;
    uint256 public randomResult;
    
    constructor(address _vrfCoordinator, address _link, bytes32 _keyHash, uint256 _fee)
        VRFConsumerBase(_vrfCoordinator, _link) {
        keyHash = _keyHash;
        fee = _fee;
    }
    
    function getRandomNumber() public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
        return requestRandomness(keyHash, fee);
    }
    
    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        randomResult = randomness;
    }
}
  1. Price feed example:
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceFeedConsumer {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    }

    function getLatestPrice() public view returns (int) {
        (,int price,,,) = priceFeed.latestRoundData();
        return price;
    }
}

Getting Started

  1. Install the Chainlink package:

    npm install @chainlink/contracts
    
  2. Import Chainlink contracts in your Solidity file:

    import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
    
  3. Set up a Chainlink node or use existing public nodes.

  4. Fund your contract with LINK tokens for oracle payments.

  5. Implement Chainlink functionality in your smart contract (see code examples above).

Competitor Comparisons

Go implementation of the Ethereum protocol

Pros of go-ethereum

  • Core Ethereum implementation, providing the foundation for the entire Ethereum network
  • Extensive documentation and community support due to its status as the official Go implementation
  • Broader scope, covering full node functionality, mining, and network protocol

Cons of go-ethereum

  • Steeper learning curve for developers not familiar with Ethereum's core architecture
  • Less focused on specific use cases, requiring more setup for specialized applications
  • Heavier resource requirements for running a full node

Code Comparison

go-ethereum (consensus algorithm):

func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
    // Ethash sealing implementation
}

Chainlink (oracle contract):

function fulfillOracleRequest(
    bytes32 _requestId,
    uint256 _payment,
    address _callbackAddress,
    bytes4 _callbackFunctionId,
    uint256 _expiration,
    bytes32 _data
) external onlyAuthorizedNode returns (bool) {
    // Oracle request fulfillment logic
}

The code snippets highlight the different focus areas of each project: go-ethereum deals with core blockchain consensus, while Chainlink specializes in oracle functionality for smart contracts.

OpenZeppelin Contracts is a library for secure smart contract development.

Pros of OpenZeppelin Contracts

  • Extensive library of reusable smart contract components
  • Well-audited and battle-tested code for enhanced security
  • Regularly updated to incorporate latest best practices

Cons of OpenZeppelin Contracts

  • Focused solely on smart contract development, lacking oracle functionality
  • May require additional integration work for complex DeFi applications

Code Comparison

OpenZeppelin Contracts (ERC20 token implementation):

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

Chainlink (Oracle price feed):

contract PriceConsumerV3 {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    }
}

OpenZeppelin Contracts provides a comprehensive set of tools for smart contract development, focusing on security and standardization. Chainlink, on the other hand, specializes in oracle services and data feeds for smart contracts. While OpenZeppelin offers a solid foundation for contract development, Chainlink excels in connecting blockchain applications with real-world data.

14,020

:warning: The Truffle Suite is being sunset. For information on ongoing support, migration options and FAQs, visit the Consensys blog. Thank you for all the support over the years.

Pros of Truffle

  • Easier to set up and use for beginners in blockchain development
  • Provides a comprehensive suite of tools for smart contract development, testing, and deployment
  • Offers a more user-friendly interface and better documentation for developers

Cons of Truffle

  • Limited to Ethereum and EVM-compatible blockchains, while Chainlink supports multiple networks
  • Lacks built-in oracle functionality, which is a core feature of Chainlink
  • Not as suitable for large-scale, production-grade blockchain applications

Code Comparison

Truffle (contract deployment):

const MyContract = artifacts.require("MyContract");

module.exports = function(deployer) {
  deployer.deploy(MyContract);
};

Chainlink (oracle interaction):

import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract MyContract is ChainlinkClient {
  function requestData() public {
    Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
    sendChainlinkRequestTo(oracle, req, fee);
  }
}

While Truffle focuses on simplifying the development and deployment process for Ethereum smart contracts, Chainlink provides robust oracle services and cross-chain interoperability. Truffle is ideal for developers starting with blockchain development, whereas Chainlink is better suited for advanced, data-driven blockchain applications requiring external data sources.

3,826

Security analysis tool for EVM bytecode. Supports smart contracts built for Ethereum, Hedera, Quorum, Vechain, Rootstock, Tron and other EVM-compatible blockchains.

Pros of Mythril

  • Focused on security analysis and vulnerability detection in smart contracts
  • Provides automated testing and symbolic execution for Ethereum bytecode
  • Offers a command-line interface for easy integration into development workflows

Cons of Mythril

  • Limited to security analysis, not a full-featured blockchain development toolkit
  • Requires more technical expertise to interpret and act on results
  • May produce false positives in some cases, requiring manual verification

Code Comparison

Mythril (vulnerability detection):

def check_integer_overflow(self, state, node):
    instruction = state.get_current_instruction()
    if instruction['opcode'] in ('ADD', 'MUL', 'SUB'):
        # Perform symbolic execution and check for overflow

Chainlink (oracle functionality):

function fulfillOracleRequest(
    bytes32 _requestId,
    uint256 _payment,
    address _callbackAddress,
    bytes4 _callbackFunctionId,
    uint256 _expiration,
    bytes32 _data
) external onlyAuthorizedNode returns (bool) {
    // Fulfill oracle request logic
}

Mythril focuses on detecting vulnerabilities in smart contracts, while Chainlink provides oracle services for connecting smart contracts with external data sources. Mythril is more suited for security auditing, whereas Chainlink is essential for building decentralized applications that require off-chain data.

4,956

A python interface for interacting with the Ethereum blockchain and ecosystem.

Pros of web3.py

  • Simpler and more lightweight, focusing specifically on Ethereum interaction
  • Easier to integrate into existing Python projects
  • More extensive documentation and examples for Python developers

Cons of web3.py

  • Limited to Ethereum blockchain interactions
  • Lacks built-in oracle functionality for off-chain data
  • Requires additional libraries for advanced smart contract interactions

Code Comparison

web3.py:

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
balance = w3.eth.get_balance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
print(w3.from_wei(balance, 'ether'))

Chainlink:

import { Chainlink, Contract, utils } from 'chainlink';

const provider = new Chainlink.providers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
const address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';
const balance = await provider.getBalance(address);
console.log(utils.formatEther(balance));

Both repositories provide tools for interacting with blockchain networks, but they serve different purposes. web3.py is focused on Ethereum interactions in Python, while Chainlink offers a broader range of features, including oracle services and cross-chain capabilities, primarily in JavaScript/TypeScript.

Aave Protocol Version 1.0 - Decentralized Lending Pools

Pros of Aave Protocol

  • Specialized in decentralized lending and borrowing, offering a wider range of DeFi services
  • More extensive documentation and guides for developers and users
  • Larger community and ecosystem of integrations with other DeFi projects

Cons of Aave Protocol

  • More complex codebase due to the variety of financial products offered
  • Higher gas costs for certain operations due to the complexity of lending/borrowing logic
  • Potentially higher security risks due to the handling of large amounts of user funds

Code Comparison

Aave Protocol (Solidity):

function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external override whenNotPaused {
    DataTypes.ReserveData storage reserve = _reserves[asset];
    address aToken = reserve.aTokenAddress;
    ValidationLogic.validateDeposit(reserve, amount);
    reserve.updateState();
}

Chainlink (Solidity):

function fulfillOracleRequest2(
    bytes32 requestId,
    uint256 payment,
    address callbackAddress,
    bytes4 callbackFunctionId,
    uint256 expiration,
    bytes calldata data
) external onlyAuthorizedSender returns (bool) {
    require(commitments[requestId].callbackAddr != address(0), "Must have a valid requestId");
    require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas");
}

Both repositories showcase advanced Solidity code, but Aave focuses on financial operations while Chainlink emphasizes oracle functionality and data handling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README


Chainlink logo


GitHub tag (latest SemVer) GitHub license GitHub workflow changeset GitHub contributors GitHub commit activity Official documentation

Chainlink expands the capabilities of smart contracts by enabling access to real-world data and off-chain computation while maintaining the security and reliability guarantees inherent to blockchain technology.

This repo contains the Chainlink core node and contracts. The core node is the bundled binary available to be run by node operators participating in a decentralized oracle network. All major release versions have pre-built docker images available for download from the Chainlink dockerhub. If you are interested in contributing please see our contribution guidelines. If you are here to report a bug or request a feature, please check currently open Issues. For more information about how to get started with Chainlink, check our official documentation. Resources for Solidity developers can be found in the Chainlink Hardhat Box.

Community

Chainlink has an active and ever growing community. Discord is the primary communication channel used for day to day communication, answering development questions, and aggregating Chainlink related content. Take a look at the community docs for more information regarding Chainlink social accounts, news, and networking.

Build Chainlink

  1. Install Go 1.22, and add your GOPATH's bin directory to your PATH
    • Example Path for macOS export PATH=$GOPATH/bin:$PATH & export GOPATH=/Users/$USER/go
  2. Install NodeJS v20 & pnpm v9 via npm.
    • It might be easier long term to use nvm to switch between node versions for different projects. For example, assuming $NODE_VERSION was set to a valid version of NodeJS, you could run: nvm install $NODE_VERSION && nvm use $NODE_VERSION
  3. Install Postgres (>= 12.x). It is recommended to run the latest major version of postgres.
    • Note if you are running the official Chainlink docker image, the highest supported Postgres version is 16.x due to the bundled client.
    • You should configure Postgres to use SSL connection (or for testing you can set ?sslmode=disable in your Postgres query string).
  4. Ensure you have Python 3 installed (this is required by solc-select which is needed to compile solidity contracts)
  5. Download Chainlink: git clone https://github.com/smartcontractkit/chainlink && cd chainlink
  6. Build and install Chainlink: make install
  7. Run the node: chainlink help

For the latest information on setting up a development environment, see the Development Setup Guide.

Apple Silicon - ARM64

Native builds on the Apple Silicon should work out of the box, but the Docker image requires more consideration.

$ docker build . -t chainlink-develop:latest -f ./core/chainlink.Dockerfile

Ethereum Execution Client Requirements

In order to run the Chainlink node you must have access to a running Ethereum node with an open websocket connection. Any Ethereum based network will work once you've configured the chain ID. Ethereum node versions currently tested and supported:

[Officially supported]

[Supported but broken] These clients are supported by Chainlink, but have bugs that prevent Chainlink from working reliably on these execution clients.

We cannot recommend specific version numbers for ethereum nodes since the software is being continually updated, but you should usually try to run the latest version available.

Running a local Chainlink node

NOTE: By default, chainlink will run in TLS mode. For local development you can disable this by using a dev build using make chainlink-dev and setting the TOML fields:

[WebServer]
SecureCookies = false
TLS.HTTPSPort = 0

[Insecure]
DevWebServer = true

Alternatively, you can generate self signed certificates using tools/bin/self-signed-certs or manually.

To start your Chainlink node, simply run:

chainlink node start

By default this will start on port 6688. You should be able to access the UI at http://localhost:6688/.

Chainlink provides a remote CLI client as well as a UI. Once your node has started, you can open a new terminal window to use the CLI. You will need to log in to authorize the client first:

chainlink admin login

(You can also set ADMIN_CREDENTIALS_FILE=/path/to/credentials/file in future if you like, to avoid having to login again).

Now you can view your current jobs with:

chainlink jobs list

To find out more about the Chainlink CLI, you can always run chainlink help.

Check out the doc pages on Jobs to learn more about how to create Jobs.

Configuration

Node configuration is managed by a combination of environment variables and direct setting via API/UI/CLI.

Check the official documentation for more information on how to configure your node.

External Adapters

External adapters are what make Chainlink easily extensible, providing simple integration of custom computations and specialized APIs. A Chainlink node communicates with external adapters via a simple REST API.

For more information on creating and using external adapters, please see our external adapters page.

Verify Official Chainlink Releases

We use cosign with OIDC keyless signing during the Build, Sign and Publish Chainlink workflow.

It is encourage for any node operator building from the official Chainlink docker image to verify the tagged release version was did indeed built from this workflow.

You will need cosign in order to do this verification. Follow the instruction here to install cosign.

# tag is the tagged release version - ie. v2.16.0
cosign verify public.ecr.aws/chainlink/chainlink:${tag} \
      --certificate-oidc-issuer https://token.actions.githubusercontent.com \
      --certificate-identity "https://github.com/smartcontractkit/chainlink/.github/workflows/build-publish.yml@refs/tags/${tag}"

Development

Running tests

  1. Install pnpm 9 via npm

  2. Install gencodec and jq to be able to run go generate ./... and make abigen

  3. Install mockery

make mockery

Using the make command will install the correct version.

  1. Build contracts:
pushd contracts
pnpm i
pnpm compile:native
popd
  1. Generate and compile static assets:
make generate
  1. Prepare your development environment:

The tests require a postgres database. In turn, the environment variable CL_DATABASE_URL must be set to value that can connect to _test database, and the user must be able to create and drop the given _test database.

Note: Other environment variables should not be set for all tests to pass

There helper script for initial setup to create an appropriate test user. It requires postgres to be running on localhost at port 5432. You will be prompted for the postgres user password

make setup-testdb

This script will save the CL_DATABASE_URL in .dbenv

Changes to database require migrations to be run. Similarly, pull'ing the repo may require migrations to run. After the one-time setup above:

source .dbenv
make testdb

If you encounter the error database accessed by other users (SQLSTATE 55006) exit status 1 and you want force the database creation then use

source .dbenv
make testdb-force
  1. Run tests:
go test ./...

Notes

  • The parallel flag can be used to limit CPU usage, for running tests in the background (-parallel=4) - the default is GOMAXPROCS
  • The p flag can be used to limit the number of packages tested concurrently, if they are interferring with one another (-p=1)
  • The -short flag skips tests which depend on the database, for quickly spot checking simpler tests in around one minute

Race Detector

As of Go 1.1, the runtime includes a data race detector, enabled with the -race flag. This is used in CI via the tools/bin/go_core_race_tests script. If the action detects a race, the artifact on the summary page will include race.* files with detailed stack traces.

It will not issue false positives, so take its warnings seriously.

For local, targeted race detection, you can run:

GORACE="log_path=$PWD/race" go test -race ./core/path/to/pkg -count 10
GORACE="log_path=$PWD/race" go test -race ./core/path/to/pkg -count 100 -run TestFooBar/sub_test

https://go.dev/doc/articles/race_detector

Fuzz tests

As of Go 1.18, fuzz tests func FuzzXXX(*testing.F) are included as part of the normal test suite, so existing cases are executed with go test.

Additionally, you can run active fuzzing to search for new cases:

go test ./pkg/path -run=XXX -fuzz=FuzzTestName

https://go.dev/doc/fuzz/

Go Modules

This repository contains three Go modules:

flowchart RL
    github.com/smartcontractkit/chainlink/v2
    github.com/smartcontractkit/chainlink/integration-tests --> github.com/smartcontractkit/chainlink/v2
    github.com/smartcontractkit/chainlink/core/scripts --> github.com/smartcontractkit/chainlink/v2

The integration-tests and core/scripts modules import the root module using a relative replace in their go.mod files, so dependency changes in the root go.mod often require changes in those modules as well. After making a change, go mod tidy can be run on all three modules using:

make gomodtidy

Solidity

Inside the contracts/ directory:

  1. Install dependencies:
pnpm i
  1. Run tests:
pnpm test

NOTE: Chainlink is currently in the process of migrating to Foundry and contains both Foundry and Hardhat tests in some versions. More information can be found here: Chainlink Foundry Documentation. Any 't.sol' files associated with Foundry tests, contained within the src directories will be ignored by Hardhat.

Code Generation

Go generate is used to generate mocks in this project. Mocks are generated with mockery and live in core/internal/mocks.

Nix

A shell.nix is provided for use with the Nix package manager. By default,we utilize the shell through Nix Flakes.

Nix defines a declarative, reproducible development environment. Flakes version use deterministic, frozen (flake.lock) dependencies to gain more consistency/reproducibility on the built artifacts.

To use it:

  1. Install nix package manager in your system.
  1. Run nix develop. You will be put in shell containing all the dependencies.
  • Optionally, nix develop --command $SHELL will make use of your current shell instead of the default (bash).
  • You can use direnv to enable it automatically when cd-ing into the folder; for that, enable nix-direnv and use flake on it.
  1. Create a local postgres database:
mkdir -p $PGDATA && cd $PGDATA/
initdb
pg_ctl -l postgres.log -o "--unix_socket_directories='$PWD'" start
createdb chainlink_test -h localhost
createuser --superuser --password chainlink -h localhost
# then type a test password, e.g.: chainlink, and set it in shell.nix CL_DATABASE_URL
  1. When re-entering project, you can restart postgres: cd $PGDATA; pg_ctl -l postgres.log -o "--unix_socket_directories='$PWD'" start Now you can run tests or compile code as usual.
  2. When you're done, stop it: cd $PGDATA; pg_ctl -o "--unix_socket_directories='$PWD'" stop

Changesets

We use changesets to manage versioning for libs and the services.

Every PR that modifies any configuration or code, should most likely accompanied by a changeset file.

To install changesets:

  1. Install pnpm if it is not already installed - docs.
  2. Run pnpm install.

Either after or before you create a commit, run the pnpm changeset command to create an accompanying changeset entry which will reflect on the CHANGELOG for the next release.

The format is based on Keep a Changelog,

and this project adheres to Semantic Versioning.

Tips

For more tips on how to build and test Chainlink, see our development tips page.

Contributing

Contributions are welcome to Chainlink's source code.

Please check out our contributing guidelines for more details.

Thank you!

NPM DownloadsLast 30 Days