WP Smart Contracts
WP Smart Contracts

Reputation: 15

Chainlink - How to pass extra parameters to the Fullfil function

I have this piece of code to call an API and return the price of a token, which is working fine:

    function requestAPIValue(string memory queryToken) public returns (bytes32 requestId) {
        Chainlink.Request memory req = buildChainlinkRequest(
            jobId32,
            address(this),
            this.fulfillValue.selector
        );

        req.add("get", string.concat(url, queryToken));
        req.add("path", path);
        req.addInt(addIntParam, multiply);

        return sendChainlinkRequest(req, oraclePayment);
    }

    function fulfillValue(bytes32 _requestId, uint256 _value)
        public
        recordChainlinkFulfillment(_requestId)
    {
        emit RequestValue(_requestId, _value);
        value = _value;
    }

But, in the fulfillValue function I need to store the price for this specific token, something like:

    function fulfillValue(bytes32 _requestId, uint256 _value, address token)
        public
        recordChainlinkFulfillment(_requestId)
    {
        emit RequestValue(_requestId, _value);
        valuesArray[token] = _value;
    }

But seems like there is no way to pass extra parameters to the buildChainlinkRequest function:

https://docs.chain.link/docs/any-api/api-reference/#buildchainlinkrequest

I think this should be a very common use case, any idea how can I do that?

Thanks

Upvotes: 0

Views: 158

Answers (1)

Andrej
Andrej

Reputation: 632

  1. Create a mapping of request IDs to token addresses, for example
    mapping(bytes32 => address) tokens;
  1. Populate it inside requestAPIValue function
    function requestAPIValue(string memory queryToken, address token) public returns (bytes32 requestId) {
        .
        .
        .

        requestId = sendChainlinkRequest(req, oraclePayment);
        tokens[requestId] = token;
    }
  1. Finally, grab it from the mapping inside the fulfillValue function since it has requestId as parameter
    function fulfillValue(bytes32 _requestId, uint256 _value)
        public
        recordChainlinkFulfillment(_requestId)
    {
        address token = tokens[_requestId];
        valuesArray[token] = _value;
    }

Upvotes: 2

Related Questions