Skip to content
Verified contractPartial

EnterpriseEscrow

Address0x3bfe293f4e51ff22986f119e28c0da563762df19
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.12

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.12+commit.f00d7308
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
Not stated
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,141,235
Creation transaction
0x82fd41f674…a85f2b1eab
Libraries
contracts/escrow/EnterpriseEscrow.sol:SponsorshipLib0x9a56…1f551e

contracts/escrow/EnterpriseEscrow.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../interfaces/IEnterpriseFeeCollector.sol";
import "../interfaces/ISubsidyProvider.sol";
import "../interfaces/IEscrowCore.sol";
import "../interfaces/IEscrowLockSubsidy.sol";
import "../interfaces/IEscrowEnterprise.sol";
import "./SponsorshipLib.sol";

/**
 * @title Enterprise Escrow contract
 *
 * @dev escrow contract between payer (aka user, consumer, etc)
 *      and payee (app/services that is performing a task which needs to be paid).
 *
 * The payer flow looks like:
 *   - payer deposits token
 *   - payer sets limit for payees (max amount, max process time)
 *   - payer can bundle multiple deposits (plain or via ERC20Permit) and authorizations
 *     in a single transaction using bundle()
 *
 *
 * The payee flow looks like:
 *   - payer asks for service (like compute) offchain
 *   - payee computes the maximum amount and locks that amount in the escrow contract
 *   - payee performs the service
 *   - payee takes the actual amount from the lock and releases back the remaining
 *   - while a lock is still active, the payee can reLock() it to change the amount and/or
 *     expiry (up or down). Every createLock check is re-evaluated against the new values, and
 *     the total lock lifetime (measured from the original creation) cannot exceed the
 *     authorization's maxLockSeconds.
 *
 * Lock-time sponsorship: a lock of gross amount L may be partly pre-funded by node-named subsidy
 * providers (ISubsidyLockProvider). The sponsored part S is held in a non-withdrawable bucket
 * (sponsoredTotal + sponsorships[lockId]); the payer only funds P = L - S. `lock.amount` always
 * stores the gross L, while `funds.locked` and `auth.currentLockedAmount` track ONLY P. The
 * enterprise fee gate still tests the GROSS lock amount L (not the payer portion P).
 */
contract EnterpriseEscrow is
    ReentrancyGuard
{
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // EnterpriseFeeCollector address
    address immutable public opcCollector;

    enum EscrowKind { COMMUNITY, ENTERPRISE }

    /*  User funds are stored per user and per token */
    struct userFunds{
        uint256 available;
        uint256 locked;
    }

    mapping(address => mapping(address => userFunds)) private funds; // user -> token -> userFunds
    // Mapping from user to an array of token addresses they have funds in
    mapping(address => address[]) private userTokens;

    // A helper mapping to avoid duplicates: user => token => hasTokenFunds
    mapping(address => mapping(address => bool)) private hasFundsInToken;

    /*  Payee authorizations are stored per user and per token */
    struct auth{
        address payee;
        uint256 maxLockedAmount;
        uint256 currentLockedAmount;
        uint256 maxLockSeconds;
        uint256 maxLockCounts;
        uint256 currentLocks;
        uint256 expiryTimestamp; // 0 = indefinite; >0 = unix ts after which no new/extended locks
    }

    mapping(address => mapping(address => auth[])) private userAuths; // user -> token -> userAuths


    // locks
    struct lock{
        uint256 jobId;
        address payer;
        uint256 amount;     // gross L (payer-funded P + sponsored S)
        uint256 expiry;     // absolute timestamp: block.timestamp + duration
        address token;
        uint256 startTime;  // block.timestamp at original createLock; preserved across reLock
    }

    mapping(address => lock[]) private locks; // locks by payee

    // sponsorship (lock-time pre-funding) state; the heavy provider-interaction logic lives in the
    // external, delegatecall-linked SponsorshipLib (which owns the Sponsorship struct + events).
    mapping(bytes32 => SponsorshipLib.Sponsorship) private sponsorships;          // lockId -> sponsorship
    mapping(address => uint256) private sponsoredTotal;               // token -> held sponsored
    mapping(address => mapping(address => uint256)) private providerReclaimable; // provider -> token -> amount

    /* structs used to bundle multiple payer actions in a single call */
    struct DepositData { address token; uint256 amount; }
    struct PermitData { address token; uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; }
    struct AuthData { address token; address payee; uint256 maxLockedAmount; uint256 maxLockSeconds; uint256 maxLockCounts; uint256 expiryTimestamp; }

    /* structs used to bundle multiple payee (job) actions in a single call */
    struct LockSubsidyData { uint256 jobId; address token; address payer; uint256 amount; uint256 expiry; uint256 jobType; address[] subsidyProviders; } // createLock & reLock
    struct ClaimData { uint256 jobId; address token; address payer; uint256 amount; bytes proof; uint256 jobType; address[] subsidyProviders; }
    struct CancelData { uint256 jobId; address token; address payer; address payee; }

    // events
    event Deposit(address indexed payer,address token,uint256 amount);
    event Withdraw(address indexed payer,address token,uint256 amount);
    event Auth(address indexed payer,address indexed payee,address token,uint256 maxLockedAmount,
        uint256 maxLockSeconds,uint256 maxLockCounts,uint256 expiryTimestamp);
    event Lock(address payer,address payee,uint256 jobId,uint256 amount,uint256 expiry,address token);
    event ReLock(address payer,address payee,uint256 jobId,uint256 oldAmount,uint256 newAmount,
        uint256 newExpiry,address token);
    event Claimed(address indexed payee,uint256 jobId,address token,address indexed payer,uint256 amount,bytes proof);
    event Canceled(address indexed payee,uint256 jobId,address token,address indexed payer,uint256 amount);
    // emitted once per contributing subsidy provider (with the actually-used subsidy and bonus)
    event Subsidized(address indexed payee,address indexed payer,uint256 jobId,address token,address provider,uint256 subsidyAmount,uint256 bonusAmount);
    // lock-time sponsorship events (match IEscrowLockSubsidy exactly)
    event LockSponsored(address indexed payer,address indexed payee,uint256 jobId,address token,address provider,uint256 amount);
    event SponsorRefunded(address indexed payer,address indexed payee,uint256 jobId,address token,address provider,uint256 amount,bool reclaimable);

    // Add constructor to set the enterprise fee collector
    constructor(address _opcCollector) {
        opcCollector = _opcCollector;
    }

    // deterministic sponsorship key for a lock
    function _lockId(address payee,address payer,uint256 jobId) internal pure returns (bytes32){
        return keccak256(abi.encode(payee,payer,jobId));
    }

    // shared parallel-array length check for the 7-array batch entrypoints
    function _eqLen7(uint256 a,uint256 b,uint256 c,uint256 d,uint256 e,uint256 f,uint256 g) internal pure {
        require(a==b && a==c && a==d && a==e && a==f && a==g,"Invalid input");
    }

    // shared createLock/reLock parameter validation
    function _validateLockParams(address payer,address token,uint256 amount,uint256 jobId) internal view {
        require(payer!=address(0),'Invalid payer');
        require(payer!=msg.sender,'Payer cannot be payee');
        require(token!=address(0),'Invalid token');
        require(amount>0,"Invalid amount");
        require(jobId>0,"Invalid jobId");
    }

    // finds the caller's (msg.sender payee) auth for (payer,token): returns a copy and its index.
    // If not found, index==length and a.payee==address(0) (callers check a.payee==msg.sender).
    function _findAuth(address payer,address token) internal view returns (auth memory a,uint256 index){
        a=auth(address(0),0,0,0,0,0,0);
        uint256 length=userAuths[payer][token].length;
        for(index=0;index<length;index++){
            if(msg.sender==userAuths[payer][token][index].payee){
                a=userAuths[payer][token][index];
                break;
            }
        }
    }

    // authorization-expiry gate for create/extend (0 = indefinite). A lock may not outlive its auth.
    function _requireAuthActive(uint256 expiryTimestamp,uint256 expiry) internal view {
        if(expiryTimestamp!=0){
            // both failures mean the authorization does not permit this lock's timing
            require(block.timestamp<=expiryTimestamp,"Auth expired");
            require(block.timestamp+expiry<=expiryTimestamp,"Auth expired");
        }
    }

    // enterprise fee gate: the configured collector must allow `token` and its fee on `amount` (gross L)
    // must stay below `amount`. Tests the GROSS lock amount, never the payer-funded portion P.
    function _requireEnterpriseFee(address token,uint256 amount) internal view {
        if(opcCollector != address(0)){
            require(
                IEnterpriseFeeCollector(opcCollector).isTokenAllowed(token),
                "This token is not allowed by enterprise fee collector"
            );
            uint256 enterpriseFee = IEnterpriseFeeCollector(opcCollector).calculateFee(token,amount);
            require(
                enterpriseFee<amount,"Amount must be higher than enterprise fee"
            );
        }
    }

    /* Payer actions  */

    /**
     * @dev deposit
     *      Called by payer to deposit funds in the contract
     *
     * @param token token to deposit
     * @param amount amount in wei to deposit
     */
    function deposit(address token,uint256 amount) external nonReentrant{
        _deposit(token,amount);
    }
    /**
     * @dev depositMultiple
     *      Called by payer to deposit multiple amount of tokens in the contract
     *
     * @param token array of tokens to deposit
     * @param amount array of amounts in wei to deposit
     */
    function depositMultiple(address[] calldata token,uint256[] calldata amount) external nonReentrant{
        require(token.length==amount.length,"Invalid input");
        for(uint256 i=0;i<token.length;i++){
            _deposit(token[i],amount[i]);
        }
    }

    /**
     * @dev depositWithPermit
     *      Called by payer to deposit funds in the contract using ERC20Permit
     *      This function allows users to deposit without a separate approval transaction
     *
     * @param token token to deposit
     * @param amount amount in wei to deposit
     * @param deadline The time at which the permit expires (unix timestamp)
     * @param v The recovery byte of the signature
     * @param r Half of the ECDSA signature pair
     * @param s Half of the ECDSA signature pair
     */
    function depositWithPermit(
        address token,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant {
        _depositWithPermit(token, amount, deadline, v, r, s);
    }
    function _depositWithPermit(
        address token,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        // Use permit to approve this contract to spend user's tokens
        IERC20Permit(token).permit(
            msg.sender,
            address(this),
            amount,
            deadline,
            v,
            r,
            s
        );
        // Deposit the tokens
        _deposit(token, amount);
    }

    /**
     * @dev bundle
     *      Called by payer to bundle multiple deposits, permit-based deposits and authorizations
     *      in a single transaction (e.g. onboarding). All operations execute as msg.sender; any
     *      sub-array may be empty.
     *
     * @param deposits array of {token, amount} for plain deposits (require prior approval)
     * @param permits array of {token, amount, deadline, v, r, s} for ERC20Permit-based deposits
     * @param auths array of {token, payee, maxLockedAmount, maxLockSeconds, maxLockCounts, expiryTimestamp}
     */
    // Reentrancy-safe: nonReentrant blocks re-entry into every state-changing entrypoint; only view
    // getters (the caller's own balances, not an oracle) are reachable during a token transfer/permit.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign
    function bundle(
        DepositData[] calldata deposits,
        PermitData[] calldata permits,
        AuthData[] calldata auths
    ) external nonReentrant {
        for(uint256 i=0;i<deposits.length;i++){
            _deposit(deposits[i].token,deposits[i].amount);
        }
        for(uint256 i=0;i<permits.length;i++){
            _depositWithPermit(permits[i].token,permits[i].amount,permits[i].deadline,permits[i].v,permits[i].r,permits[i].s);
        }
        for(uint256 i=0;i<auths.length;i++){
            _authorize(auths[i].token,auths[i].payee,auths[i].maxLockedAmount,auths[i].maxLockSeconds,auths[i].maxLockCounts,auths[i].expiryTimestamp);
        }
    }

    /**
     * @dev bundleJobs
     *      Called by a payee (e.g. a node servicing many jobs) to batch payee-side lock operations
     *      in a single transaction. Operations run as msg.sender in a fixed order:
     *      claims -> cancels -> creates -> reLocks, so lock slots / locked amounts freed by claims and
     *      cancels are available before new locks are created. Any sub-array may be empty.
     *
     * @param claims array of ClaimData passed to claimLock
     * @param cancels array of {jobId, token, payer, payee} passed to cancelExpiredLock
     * @param newLocks array of LockSubsidyData passed to createLock
     * @param reLockOps array of LockSubsidyData passed to reLock
     */
    // Reentrancy-safe: nonReentrant blocks re-entry into every state-changing entrypoint, including
    // the subsidy-provider callbacks and token moves inside each lock/claim; only view getters reachable.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function bundleJobs(
        ClaimData[] calldata claims,
        CancelData[] calldata cancels,
        LockSubsidyData[] calldata newLocks,
        LockSubsidyData[] calldata reLockOps
    ) external nonReentrant {
        for(uint256 i=0;i<claims.length;i++){
            _claimLock(claims[i]);
        }
        for(uint256 i=0;i<cancels.length;i++){
            _cancelExpiredLock(cancels[i].jobId,cancels[i].token,cancels[i].payer,cancels[i].payee);
        }
        for(uint256 i=0;i<newLocks.length;i++){
            _createLock(newLocks[i].jobId,newLocks[i].token,newLocks[i].payer,newLocks[i].amount,newLocks[i].expiry,newLocks[i].jobType,newLocks[i].subsidyProviders);
        }
        for(uint256 i=0;i<reLockOps.length;i++){
            _reLock(reLockOps[i].jobId,reLockOps[i].token,reLockOps[i].payer,reLockOps[i].amount,reLockOps[i].expiry,reLockOps[i].jobType,reLockOps[i].subsidyProviders);
        }
    }

    function _deposit(address token,uint256 amount) internal{
        require(token!=address(0),"Invalid token address");
        funds[msg.sender][token].available+=amount;
        if (!hasFundsInToken[msg.sender][token]) {
            userTokens[msg.sender].push(token);
            hasFundsInToken[msg.sender][token] = true;
        }
        emit Deposit(msg.sender,token,amount);
        uint256 balanceBefore = IERC20(token).balanceOf(address(this));
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        require(
            IERC20(token).balanceOf(address(this)) >= balanceBefore.add(amount),
            "Transfer amount is too low"
        );

    }


    /**
     * @dev withdraw
     *      Called by payer to withdraw available (not locked) funds from the contract
     *
     * @param token array of tokens to withdraw
     * @param amount array of amounts in wei to withdraw
     */
    function withdraw(address[] calldata token,uint256[] calldata amount) external nonReentrant{
        require(token.length==amount.length,"Invalid input");
        for(uint256 i=0;i<token.length;i++){
            _withdraw(token[i],amount[i]);
        }
    }
    function _withdraw(address token,uint256 amount) internal{
        if(funds[msg.sender][token].available>=amount){
            funds[msg.sender][token].available-=amount;
            if(funds[msg.sender][token].available==0){
                address[] storage tokens = userTokens[msg.sender];
                for (uint256 i = 0; i < tokens.length; i++) {
                    if (tokens[i] == token) {
                        tokens[i] = tokens[tokens.length - 1]; // overwrite with last element
                        tokens.pop(); // remove last element
                        break;
                    }
                }
                // Update interaction status
                hasFundsInToken[msg.sender][token] = false;
            }
            emit Withdraw(msg.sender,token,amount);
            IERC20(token).safeTransfer(
                msg.sender,
                amount
            );

        }
    }
    function getUserTokens(address user) external view returns (address[] memory) {
        return userTokens[user];
    }


    /**
     * @dev authorize
     *      Called by payer to authorize a payee to lock and claim funds
     *
     * @param token token to lock
     * @param payee payee address
     * @param maxLockedAmount maximum amount locked by payee in one lock
     * @param maxLockSeconds maximum lock duration in seconds
     * @param maxLockCounts maximum locks held by this payee
     * @param expiryTimestamp unix ts after which the auth can no longer create/extend locks (0 = never)
     */
    function authorize(address token,address payee,uint256 maxLockedAmount,
        uint256 maxLockSeconds,uint256 maxLockCounts,uint256 expiryTimestamp) external nonReentrant{
        _authorize(token,payee,maxLockedAmount,maxLockSeconds,maxLockCounts,expiryTimestamp);
    }

    /**
     * @dev authorizeMultiple
     *      Called by payer to authorize multiple payees to lock and claim funds
     *
     * @param token array of tokens to lock
     * @param payee array of payees addresses
     * @param maxLockedAmount array of maximum amount locked by payee in one lock
     * @param maxLockSeconds array of maximum lock duration in seconds
     * @param maxLockCounts array of maximum locks held by this payee
     * @param expiryTimestamp array of auth expiry timestamps (0 = never)
     */
    function authorizeMultiple(address[] calldata token,address[] calldata payee,uint256[] calldata maxLockedAmount,
        uint256[] calldata maxLockSeconds,uint256[] calldata maxLockCounts,uint256[] calldata expiryTimestamp) external nonReentrant{
            require(token.length==payee.length &&
                    token.length==maxLockedAmount.length &&
                    token.length==maxLockSeconds.length &&
                    token.length==maxLockCounts.length &&
                    token.length==expiryTimestamp.length,"Invalid input");
            for(uint256 i=0;i<token.length;i++){
                _authorize(token[i],payee[i],maxLockedAmount[i],maxLockSeconds[i],maxLockCounts[i],expiryTimestamp[i]);
            }
    }

    function _authorize(address token,address payee,uint256 maxLockedAmount,
        uint256 maxLockSeconds,uint256 maxLockCounts,uint256 expiryTimestamp) internal{

        require(token!=address(0),'Invalid token');
        require(payee!=address(0),'Invalid payee');
        uint256 i;
        uint256 length=userAuths[msg.sender][token].length;
        for(i=0;i<length;i++){
            if(userAuths[msg.sender][token][i].payee==payee){
                userAuths[msg.sender][token][i].maxLockedAmount=maxLockedAmount;
                userAuths[msg.sender][token][i].maxLockSeconds=maxLockSeconds;
                userAuths[msg.sender][token][i].maxLockCounts=maxLockCounts;
                userAuths[msg.sender][token][i].expiryTimestamp=expiryTimestamp;
                break;
            }
        }
        if(i==length){ //not found
            userAuths[msg.sender][token].push(auth(payee,maxLockedAmount,0,maxLockSeconds,maxLockCounts,0,expiryTimestamp));
        }
        emit Auth(msg.sender,payee,token,maxLockedAmount,maxLockSeconds,maxLockCounts,expiryTimestamp);

    }

    /* Payer view actions  */
    /**
     * @dev getFunds
     *      Returns funds information for caller
     *
     * @param token token
     */
    function getFunds(address token) public view returns (userFunds memory){
        return(funds[msg.sender][token]);
    }
    /**
     * @dev getUserFunds
     *      Returns funds information for a specific payer
     *
     * @param payer payer
     * @param token token
     */
    function getUserFunds(address payer,address token) public view returns (userFunds memory){
        return(funds[payer][token]);
    }

    /**
     * @dev getLocks
     *      Returns all locks, filtered
     *
     * @param token token to filter (zero address means any)
     * @param payer payer to filter (zero address means any)
     * @param payee payee to filter (required)
     */
    function getLocks(address token,address payer,address payee) public view returns (lock[] memory){
        require(payee!=address(0),'Invalid payee');
        // since solidty does not supports dynamic memory arrays, we need to calculate the return size first
        uint256 size=0;
        uint256 length=locks[payee].length;
        for(uint256 i=0;i<length;i++){
            if(
                (address(token)==address(0) || address(token)==locks[payee][i].token) ||
                (address(payer)==address(0) || address(payer)==locks[payee][i].payer)
            ){
                size++;
            }
        }

        lock[] memory tempPendings=new lock[](size);
        size=0;
        for(uint256 i=0;i<length;i++){
            if(
                (address(token)==address(0) || address(token)==locks[payee][i].token) ||
                (address(payer)==address(0) || address(payer)==locks[payee][i].payer)
            ){
                tempPendings[size]=locks[payee][i];
                size++;
            }
        }
        return(tempPendings);
    }


    /**
     * @dev getAuthorizations
     *      Returns all auths
     *
     * @param token token, required
     * @param payer payer, required
     * @param payee payee to filter (zero address means any)
     */
    function getAuthorizations(address token,address payer,address payee) public view returns (auth[] memory){
        require(payer!=address(0),'Invalid payer');
        require(token!=address(0),'Invalid token');
        // since solidty does not supports dynamic memory arrays, we need to calculate the return size first
        uint256 size=0;
        uint256 length=userAuths[payer][token].length;
        for(uint256 i=0;i<length;i++){
            if(address(payee)==address(0) || address(payee)==userAuths[payer][token][i].payee) size++;
        }
        auth[] memory tempAuths=new auth[](size);
        size=0;
        for(uint256 i=0;i<length;i++){
            if(address(payee)==address(0) || address(payee)==userAuths[payer][token][i].payee){
                tempAuths[size]=userAuths[payer][token][i];
                size++;
            }
        }
        return(tempAuths);
    }

    /* Payee  functions   */

    /**
     * @dev createLock
     *      Called by payee to create a lock. May be partly pre-funded by subsidy providers.
     *
     * @param jobId jobId, required
     * @param token token, required
     * @param payer payer address
     * @param amount gross amount in wei to lock
     * @param expiry expiry timestamp (relative seconds)
     * @param jobType opaque category forwarded to the lock providers
     * @param subsidyProviders list of ISubsidyLockProvider addresses (empty = payer-funded)
     */
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function createLock(uint256 jobId,address token,address payer,uint256 amount,uint256 expiry,
        uint256 jobType,address[] calldata subsidyProviders) external nonReentrant{
        _createLock(jobId,token,payer,amount,expiry,jobType,subsidyProviders);
    }
    /**
     * @dev createLocks
     *      Called by payee to create multiple locks
     *
     * @param jobId array of jobIds
     * @param token array of tokens
     * @param payer array of payer addresses
     * @param amount array of gross amounts in wei to lock
     * @param expiry array of expiry timestamps
     * @param jobType array of jobTypes
     * @param subsidyProviders array of provider lists (one per lock)
     */
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function createLocks(uint256[] calldata jobId,address[] calldata token,
        address[] calldata payer,uint256[] calldata amount,uint256[] calldata expiry,
        uint256[] calldata jobType,address[][] calldata subsidyProviders) external nonReentrant{

        _eqLen7(jobId.length,token.length,payer.length,amount.length,expiry.length,jobType.length,subsidyProviders.length);
        _batchLockMem(false,jobId,token,payer,amount,expiry,jobType,subsidyProviders);
    }
    // loops create/reLock over parallel arrays; memory params (single stack slots) keep the 7-way loop
    // within viaIR's stack budget. calldata arrays are copied to memory at the call site. `relock`
    // selects reLock vs createLock so a single helper serves both plural entrypoints.
    function _batchLockMem(bool relock,uint256[] memory jobId,address[] memory token,address[] memory payer,
        uint256[] memory amount,uint256[] memory expiry,uint256[] memory jobType,
        address[][] memory subsidyProviders) internal {
        for(uint256 i=0;i<jobId.length;i++){
            if(relock) _reLock(jobId[i],token[i],payer[i],amount[i],expiry[i],jobType[i],subsidyProviders[i]);
            else _createLock(jobId[i],token[i],payer[i],amount[i],expiry[i],jobType[i],subsidyProviders[i]);
        }
    }
    function _createLock(uint256 jobId,address token,address payer,uint256 amount,uint256 expiry,
        uint256 jobType,address[] memory subsidyProviders) internal {
        _validateLockParams(payer,token,amount,jobId);
        (auth memory tempAuth,uint256 index)=_findAuth(payer,token);
        require(tempAuth.payee==msg.sender,"No auth found");
        require(expiry<=tempAuth.maxLockSeconds,"Expiry too high");
        _requireAuthActive(tempAuth.expiryTimestamp,expiry);
        require(tempAuth.currentLocks<tempAuth.maxLockCounts,"Exceeds maxLockCounts");
        // check jobId uniqueness for this payee/payer
        uint256 length=locks[msg.sender].length;
        for(uint256 i=0;i<length;i++){
            if(locks[msg.sender][i].payer==payer && locks[msg.sender][i].jobId==jobId){
                revert("JobId already exists");
            }
        }
        // enterprise fee gate: tests the GROSS lock amount L (not the payer portion P)
        _requireEnterpriseFee(token,amount);
        // lock-time sponsorship (library updates sponsorships[lockId].total/jobType and sponsoredTotal)
        bytes32 lockId=_lockId(msg.sender,payer,jobId);
        require(sponsorships[lockId].total==0,"JobId already exists"); // stale sponsorship for reused key
        uint256 S=SponsorshipLib.applyLockSubsidies(sponsorships,sponsoredTotal,jobId,lockId,msg.sender,payer,token,jobType,amount,subsidyProviders);
        uint256 P=amount-S; // S<=amount by the per-provider cap
        // auth caps apply to the payer-funded portion only; moves P available->locked (check-then-apply)
        _addPayerLocked(payer,token,index,tempAuth.maxLockedAmount,tempAuth.currentLockedAmount,P);
        userAuths[payer][token][index].currentLocks+=1;
        // create the lock (amount = gross L)
        locks[msg.sender].push(lock(jobId,payer,amount,block.timestamp+expiry,token,block.timestamp));
        emit Lock(payer,msg.sender,jobId,amount,expiry,token);
    }

    /**
     * @dev reLock
     *      Called by payee to change the amount and/or expiry of an existing, still active lock.
     *      Both amount and expiry can go up or down. All createLock checks (including the enterprise
     *      fee gate) are re-evaluated against the new values, and the total lock lifetime (measured
     *      from the original creation) cannot exceed the authorization's maxLockSeconds. jobId and
     *      the original startTime are preserved.
     *      Sponsorship-aware: grow re-quotes the provider list, shrink refunds sponsors in list order.
     *
     * @param jobId jobId, required (identifies the lock together with token and payer)
     * @param token token, required
     * @param payer payer address
     * @param amount new gross amount in wei to lock
     * @param expiry new expiry, relative seconds from now
     * @param jobType opaque category forwarded to the lock providers (used on grow)
     * @param subsidyProviders list of ISubsidyLockProvider addresses to consult on grow
     */
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function reLock(uint256 jobId,address token,address payer,uint256 amount,uint256 expiry,
        uint256 jobType,address[] calldata subsidyProviders) external nonReentrant{
        _reLock(jobId,token,payer,amount,expiry,jobType,subsidyProviders);
    }
    /**
     * @dev reLocks
     *      Called by payee to reLock multiple existing locks
     *
     * @param jobId array of jobIds
     * @param token array of tokens
     * @param payer array of payer addresses
     * @param amount array of new gross amounts in wei to lock
     * @param expiry array of new expiries, relative seconds from now
     * @param jobType array of jobTypes
     * @param subsidyProviders array of provider lists (one per reLock)
     */
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function reLocks(uint256[] calldata jobId,address[] calldata token,
        address[] calldata payer,uint256[] calldata amount,uint256[] calldata expiry,
        uint256[] calldata jobType,address[][] calldata subsidyProviders) external nonReentrant{

        _eqLen7(jobId.length,token.length,payer.length,amount.length,expiry.length,jobType.length,subsidyProviders.length);
        _batchLockMem(true,jobId,token,payer,amount,expiry,jobType,subsidyProviders);
    }
    function _reLock(uint256 jobId,address token,address payer,uint256 amount,uint256 expiry,
        uint256 jobType,address[] memory subsidyProviders) internal {
        _validateLockParams(payer,token,amount,jobId);
        // find the existing lock
        lock memory tempLock=lock(0,address(0),0,0,address(0),0);
        uint256 lockIndex;
        uint256 length=locks[msg.sender].length;
        for(lockIndex=0;lockIndex<length;lockIndex++){
            if(
                payer==locks[msg.sender][lockIndex].payer &&
                jobId==locks[msg.sender][lockIndex].jobId &&
                token==locks[msg.sender][lockIndex].token
            ){
                tempLock=locks[msg.sender][lockIndex];
                break;
            }
        }
        require(tempLock.payer==payer,"Lock not found");
        require(tempLock.expiry>=block.timestamp,"Lock expired");
        // find the auth
        (auth memory tempAuth,uint256 index)=_findAuth(payer,token);
        require(tempAuth.payee==msg.sender,"No auth found");
        require(block.timestamp+expiry<=tempLock.startTime+tempAuth.maxLockSeconds,"Expiry too high");
        _requireAuthActive(tempAuth.expiryTimestamp,expiry);
        // enterprise fee gate with the new amount: tests the GROSS lock amount L (not the payer portion P)
        _requireEnterpriseFee(token,amount);
        bytes32 lockId=_lockId(msg.sender,payer,jobId);
        uint256 S_old=sponsorships[lockId].total;
        uint256 P_old=tempLock.amount-S_old; // gross L_old - S_old
        if(amount<tempLock.amount){
            // SHRINK: payer side takes the floor, sponsored side absorbs the rounding
            uint256 P_new=(P_old*amount)/tempLock.amount;
            uint256 payerRefund=P_old-P_new;
            funds[payer][token].available+=payerRefund;
            funds[payer][token].locked-=payerRefund;
            userAuths[payer][token][index].currentLockedAmount=tempAuth.currentLockedAmount-payerRefund;
            if(S_old>0){
                SponsorshipLib.shrinkSponsored(sponsorships,sponsoredTotal,providerReclaimable,lockId,msg.sender,payer,jobId,token,S_old,amount-P_new);
            }
        } else if(amount>tempLock.amount){
            // GROW: re-quote providers for the delta, payer covers the rest (library merges S_add &
            // updates sponsorships[lockId].total/jobType and sponsoredTotal)
            uint256 delta=amount-tempLock.amount;
            uint256 S_add=SponsorshipLib.applyLockSubsidies(sponsorships,sponsoredTotal,jobId,lockId,msg.sender,payer,token,jobType,delta,subsidyProviders);
            uint256 payerAdd=delta-S_add; // >=0 by the per-provider cap
            _addPayerLocked(payer,token,index,tempAuth.maxLockedAmount,tempAuth.currentLockedAmount,payerAdd);
        }
        // else expiry-only: no backing change
        // update the lock in place (jobId and startTime preserved; amount = gross L_new)
        locks[msg.sender][lockIndex].amount=amount;
        locks[msg.sender][lockIndex].expiry=block.timestamp+expiry;
        emit ReLock(payer,msg.sender,jobId,tempLock.amount,amount,expiry,token);
    }

     /**
     * @dev claimLock
     *      Called by payee to claim a lock (fully or partial)
     *      Must match a previous lock. The node may supply a jobType and a list of subsidy providers
     *      that may sponsor part of the payer's cost and/or add a bonus for the node (empty list =
     *      no subsidy).
     *
     * @param jobId jobId, required
     * @param token token, required
     * @param payer payer address
     * @param amount amount in wei to claim
     * @param proof job proof
     * @param jobType opaque category forwarded to the providers
     * @param subsidyProviders list of ISubsidyProvider addresses to consult
     */
    // Reentrancy-safe: nonReentrant blocks re-entry, including the subsidy-provider callback and the
    // token pull; only view getters are reachable during the external calls.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function claimLock(uint256 jobId,address token,address payer,uint256 amount,
        bytes calldata proof,uint256 jobType,address[] calldata subsidyProviders)
        external nonReentrant{
            ClaimData memory c = ClaimData(jobId,token,payer,amount,proof,jobType,subsidyProviders);
            _claimLock(c);
    }

    /**
     * @dev claimLocks
     *      Called by payee to claim locks (fully or partial) and keeps funds in the contract
     *      Must match previous locks. Parallel jobType and subsidyProviders arrays carry the
     *      per-claim subsidy parameters (empty inner list = no subsidy).
     *
     * @param jobId array of jobIds
     * @param token array of tokens
     * @param payer array of payer addresses
     * @param amount array amounts in wei to claim
     * @param proof array of job proofs
     * @param jobType array of jobTypes
     * @param subsidyProviders array of subsidy-provider lists (one per claim)
     */
    // Reentrancy-safe: nonReentrant blocks re-entry, including the subsidy-provider callbacks and the
    // token pulls; only view getters are reachable during the external calls.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function claimLocks(uint256[] calldata jobId,address[] calldata token,
        address[] calldata payer,uint256[] calldata amount,bytes[] calldata proof,
        uint256[] calldata jobType,address[][] calldata subsidyProviders) external nonReentrant{

            _claimLocksMem(jobId,token,payer,amount,proof,jobType,subsidyProviders);
    }
    // loops _claimLock over parallel arrays; params are memory (single stack slots) so the 7-way loop
    // does not blow the stack. calldata arrays are copied to memory implicitly at the call site.
    // Validates the parallel-array lengths once here (shared by both claimLocks entrypoints).
    function _claimLocksMem(uint256[] memory jobId,address[] memory token,address[] memory payer,
        uint256[] memory amount,bytes[] memory proof,uint256[] memory jobType,
        address[][] memory subsidyProviders) internal {
        _eqLen7(jobId.length,token.length,payer.length,amount.length,proof.length,jobType.length,subsidyProviders.length);
        for(uint256 i=0;i<jobId.length;i++){
            ClaimData memory c = ClaimData(jobId[i],token[i],payer[i],amount[i],proof[i],jobType[i],subsidyProviders[i]);
            _claimLock(c);
        }
    }
    /**
     * @dev claimLockAndWithdraw
     *      Called by payee to claim lock (fully or partial) and withdraw funds
     *      Must match previous lock. Supports the same subsidy parameters as claimLock.
     *
     * @param jobId jobId, required
     * @param token token, required
     * @param payer payer address
     * @param amount amount in wei to claim
     * @param proof job proof
     * @param jobType opaque category forwarded to the providers
     * @param subsidyProviders list of ISubsidyProvider addresses to consult
     */
    // Reentrancy-safe: nonReentrant blocks re-entry, including the subsidy-provider callback and the
    // token pull; only view getters are reachable during the external calls.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function claimLockAndWithdraw(uint256 jobId,address token,address payer,
        uint256 amount,bytes calldata proof,uint256 jobType,address[] calldata subsidyProviders)
        external nonReentrant{
            ClaimData memory c = ClaimData(jobId,token,payer,amount,proof,jobType,subsidyProviders);
            _claimLock(c);
            _withdraw(token,funds[msg.sender][token].available);
    }
    /**
     * @dev claimLocksAndWithdraw
     *      Called by payee to claim locks (fully or partial) and withdraw funds
     *      Must match previous locks. Parallel jobType and subsidyProviders arrays carry the
     *      per-claim subsidy parameters.
     *
     * @param jobId array of jobIds
     * @param token array of tokens
     * @param payer array of payer addresses
     * @param amount array amounts in wei to claim
     * @param proof array of job proofs
     * @param jobType array of jobTypes
     * @param subsidyProviders array of subsidy-provider lists (one per claim)
     */
    // Reentrancy-safe: nonReentrant blocks re-entry, including the subsidy-provider callbacks and the
    // token pulls; only view getters are reachable during the external calls.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function claimLocksAndWithdraw(uint256[] calldata jobId,address[] calldata token,
        address[] calldata payer,uint256[] calldata amount,bytes[] calldata proof,
        uint256[] calldata jobType,address[][] calldata subsidyProviders) external nonReentrant{
        _claimLocksMem(jobId,token,payer,amount,proof,jobType,subsidyProviders);
        _withdrawAvailable(token);
    }

    // withdraw all of msg.sender's available balance for each listed token (used by *AndWithdraw)
    function _withdrawAvailable(address[] calldata token) internal {
        for(uint256 i=0;i<token.length;i++){
            if(funds[msg.sender][token[i]].available>0){
                _withdraw(token[i],funds[msg.sender][token[i]].available);
            }
        }
    }

    // Reentrancy-safe: reached only via nonReentrant entrypoints, so re-entry is impossible. Makes
    // external calls (subsidy-provider callbacks, the guarded subsidy pull, refund pushes and the fee
    // transfer); the funds/userTokens writes cannot be exploited because re-entry is blocked.
    // slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events
    function _claimLock(ClaimData memory c) internal {
        require(c.payer!=address(0),'Invalid payer');
        require(c.token!=address(0),'Invalid token');
        require(c.jobId>0,'Invalid jobId');
        lock memory tempLock=lock(0,address(0),0,0,address(0),0);
        uint256 index;
        uint256 length=locks[msg.sender].length;
        for(index=0;index<length;index++){
            if(
                c.payer==locks[msg.sender][index].payer &&
                c.jobId==locks[msg.sender][index].jobId &&
                c.token==locks[msg.sender][index].token

            ) {
                tempLock=locks[msg.sender][index];
                break;
            }
        }
        require(tempLock.payer==c.payer,"Lock not found");
        if(tempLock.expiry<block.timestamp){
            //we are too late, cancel the lock
            _cancelExpiredLock(c.jobId,c.token,c.payer,msg.sender);
            return;
        }
        require(tempLock.amount>=c.amount,"Amount too high"); // gross L cap

        bytes32 lockId=_lockId(msg.sender,c.payer,c.jobId);
        uint256 S=sponsorships[lockId].total;
        uint256 P=tempLock.amount-S; // L - S (payer-funded portion)
        uint256 fromSponsored = c.amount<S ? c.amount : S; // sponsored-funded part of the claim

        //update auths (only the payer-funded portion P was ever tracked)
        _releasePayerLocked(c.payer,c.token,msg.sender,P);
        //update user funds: return the payer's unclaimed remainder and unlock P
        funds[c.payer][c.token].available+=P-(c.amount-fromSponsored);
        funds[c.payer][c.token].locked-=P;
        _trackToken(c.payer,c.token);
        //claim-time subsidy (released to payer), capped at the payer-funded claimed portion; bonus basis = C
        (uint256 subsidy,uint256 bonus)=_applySubsidiesCapped(c.jobId,c.payer,c.token,c.jobType,c.amount,c.amount-fromSponsored,c.subsidyProviders);
        //release the subsidy back to the payer (bonus is NOT released to the payer)
        if(subsidy>0){
            funds[c.payer][c.token].available+=subsidy;
        }
        // credit the node payout (fee charged on amount+bonus) and transfer the fee out last
        _creditPayout(c.token,c.amount+bonus);
        // refund unused sponsored to providers (library consumes fromSponsored in list order, pushes +
        // notifies, decrements sponsoredTotal by S and deletes the sponsorship entry)
        if(S>0){
            SponsorshipLib.settleRefund(sponsorships,sponsoredTotal,providerReclaimable,lockId,msg.sender,c.payer,c.jobId,c.token,fromSponsored);
        }
        //delete the lock
        if(index<locks[msg.sender].length-1){
            locks[msg.sender][index]=locks[msg.sender][locks[msg.sender].length-1];
        }
        locks[msg.sender].pop();
        emit Claimed(msg.sender,c.jobId,c.token,c.payer,c.amount,c.proof);
    }

    // credit the node (msg.sender) payout for `payoutBase` (= amount + bonus), then transfer the OPC
    // fee out last. fee is charged on payoutBase. The fee is CAPPED at payoutBase: a (trusted but
    // possibly misconfigured) collector returning fee >= payoutBase must neither underflow-revert the
    // claim (DoS) NOR cause the escrow to transfer out more than this claim's base (which would dip
    // the shared pool and break solvency). Capping preserves both liveness and solvency; the node
    // simply receives 0 and the collector receives at most payoutBase.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events
    function _creditPayout(address token,uint256 payoutBase) internal {
        uint256 payout = payoutBase;
        if(opcCollector != address(0)){
            uint256 feeAmount = IEnterpriseFeeCollector(opcCollector).calculateFee(token,payoutBase);
            if(feeAmount > payoutBase) feeAmount = payoutBase; // cap: never pay out more than the base
            payout = payoutBase - feeAmount;
            funds[msg.sender][token].available+=payout;
            _trackToken(msg.sender,token);
            if(feeAmount > 0){
                IERC20(token).safeTransfer(opcCollector, feeAmount);
            }
            return;
        }
        funds[msg.sender][token].available+=payout;
        _trackToken(msg.sender,token);
    }

    // helper: make sure `token` is tracked in `user`'s userTokens list (for getUserTokens-based UIs)
    function _trackToken(address user,address token) internal {
        if (!hasFundsInToken[user][token]) {
            userTokens[user].push(token);
            hasFundsInToken[user][token] = true;
        }
    }

    // check-then-apply the payer-funded addition `add`: require funds + auth cap, then move
    // `add` available->locked and set currentLockedAmount. Shared by createLock and reLock-grow.
    function _addPayerLocked(address payer,address token,uint256 index,uint256 maxLocked,
        uint256 currentLocked,uint256 add) internal {
        require(funds[payer][token].available>=add,"Payer does not have enough funds");
        require(currentLocked+add<=maxLocked,"Exceeds maxLockedAmount");
        userAuths[payer][token][index].currentLockedAmount=currentLocked+add;
        funds[payer][token].available-=add;
        funds[payer][token].locked+=add;
    }

    // releases the payer-funded `release` from the payee's auth slot (currentLockedAmount, currentLocks).
    // Shared by _claimLock and _settleCancel.
    function _releasePayerLocked(address payer,address token,address payee,uint256 release) internal {
        uint256 length=userAuths[payer][token].length;
        for(uint256 i=0;i<length;i++){
            if(userAuths[payer][token][i].payee==payee){
                userAuths[payer][token][i].currentLockedAmount-=release;
                userAuths[payer][token][i].currentLocks-=1;
            }
        }
    }

    /**
     * @dev _applySubsidiesCapped
     *      Claim-time reimbursement subsidy. Consults each unique non-payer provider for a subsidy
     *      (released to the payer, capped at `subsidyCap`) and a bonus (added to the node payout,
     *      uncapped). `amount` is the bonus/pct basis forwarded to the provider (the full claim C),
     *      while `subsidyCap` bounds only the subsidy (the payer-funded claimed portion). When
     *      subsidyCap == amount this is the pre-sponsorship behaviour. One bad provider/token must
     *      never brick the claim (low-level quote, reject-partial pull).
     * @return totalSubsidy sum of the accepted subsidies (released to the payer)
     * @return totalBonus   sum of the accepted bonuses (added to the node payout)
     */
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events,calls-loop
    function _applySubsidiesCapped(uint256 jobId,address payer,address token,uint256 jobType,uint256 amount,
        uint256 subsidyCap,address[] memory subsidyProviders) internal returns (uint256 totalSubsidy,uint256 totalBonus){
        uint256 remaining = subsidyCap; // subsidy cap only; bonus is uncapped
        for(uint256 i=0;i<subsidyProviders.length;i++){
            address provider = subsidyProviders[i];
            // never pull from the payer's own wallet (MED mitigation); do NOT break on remaining==0,
            // a later provider can still add a bonus.
            if(provider==payer) continue;
            // skip a provider already processed earlier in this list, so a repeated entry cannot stack
            // multiple grants. Each unique provider is consulted at most once per claim.
            bool duplicate=false;
            for(uint256 j=0;j<i;j++){ if(subsidyProviders[j]==provider){ duplicate=true; break; } }
            if(duplicate) continue;
            (uint256 usedSub,uint256 usedBonus)=_consultProvider(jobId,payer,token,jobType,amount,provider,remaining);
            totalSubsidy += usedSub;
            totalBonus += usedBonus;
            remaining -= usedSub; // usedSub <= remaining, cannot underflow
        }
    }

    // Consults one provider: asks for a quote via a LOW-LEVEL call (never reverts the claim - a failed
    // call OR returndata shorter than 64 bytes contributes 0), caps the subsidy at `remaining`, and
    // pulls subsidy+bonus with a guarded low-level call. Returns the actually-accepted amounts.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events,calls-loop
    function _consultProvider(uint256 jobId,address payer,address token,uint256 jobType,uint256 amount,
        address provider,uint256 remaining) internal returns (uint256 usedSub,uint256 usedBonus){
        // EOA / non-contract provider: nothing to consult.
        if(provider.code.length==0) return (0,0);
        (bool ok,bytes memory data)=provider.call(
            abi.encodeWithSelector(ISubsidyProvider.onSubsidyClaim.selector,
                msg.sender,payer,jobType,token,amount,remaining));
        // a reverting or short-returning (wrong-selector / non-conforming) provider contributes 0
        if(!ok || data.length<64) return (0,0);
        (uint256 subsidyAmount,uint256 bonusAmount)=abi.decode(data,(uint256,uint256));
        uint256 wantSubsidy = subsidyAmount < remaining ? subsidyAmount : remaining; // cap
        // OVERFLOW-SAFE COMBINE: skip a bogus quote (e.g. bonus ~2^256-1) instead of a checked-add revert.
        if(bonusAmount > type(uint256).max - wantSubsidy) return (0,0);
        uint256 wantTotal = wantSubsidy + bonusAmount; // bonus is uncapped
        if(wantTotal==0) return (0,0);
        // guarded pull; reject-partial (received < wantTotal -> skip via _pullExact).
        if(!_pullExact(token,provider,wantTotal)) return (0,0);
        emit Subsidized(msg.sender,payer,jobId,token,provider,wantSubsidy,bonusAmount);
        return (wantSubsidy,bonusAmount);
    }

    // guarded token pull: low-level transferFrom(provider -> escrow) whose balanceOf-diff is the sole
    // source of truth. Returns true only if the escrow received the FULL wantTotal (reject-partial).
    // Never reverts on a lying/short-returning token (low-level call, no bool decode).
    // slither-disable-next-line reentrancy-benign,reentrancy-events
    function _pullExact(address token,address provider,uint256 wantTotal) internal returns (bool){
        uint256 balBefore = IERC20(token).balanceOf(address(this));
        (bool ok,)=token.call(abi.encodeWithSelector(IERC20.transferFrom.selector,provider,address(this),wantTotal));
        if(!ok) return false;
        uint256 balAfter = IERC20(token).balanceOf(address(this));
        uint256 received = balAfter>=balBefore ? balAfter-balBefore : 0; // underflow-guarded
        return received>=wantTotal;
    }

    /**
     * @dev cancelExpiredLock
     *      Can be called by anyone to release an expired lock
     *
     * @param jobId jobId, if 0 matches any jobId
     * @param token token (zero address means any)
     * @param payer payer address (zero address means any)
     * @param payee payee address (required)
     */
    function cancelExpiredLock(uint256 jobId,address token,address payer,address payee) external nonReentrant{
        _cancelExpiredLock(jobId,token,payer,payee);

    }
    /**
     * @dev cancelExpiredLocks
     *      Can be called by anyone to release an expired locks
     *
     * @param jobId jobId, if 0 matches any jobId
     * @param token token (zero address means any)
     * @param payer payer address (zero address means any)
     * @param payee payee address (required)
     */
    function cancelExpiredLocks(uint256[] calldata jobId,address[] calldata token,address[] calldata payer,
        address[] calldata payee) external nonReentrant{
            require(jobId.length==token.length &&
            jobId.length==payer.length &&
            jobId.length==payee.length,"Invalid input");
            for(uint256 i=0;i<jobId.length;i++){
                _cancelExpiredLock(jobId[i],token[i],payer[i],payee[i]);
            }
    }

    // settles one cancelled lock: releases the payer-funded P (NOT gross L — the critical drain fix),
    // refunds the full sponsored S to providers, and clears the sponsorship. Keyed by the matched
    // lock's OWN payer/jobId/token. Extracted to keep _cancelExpiredLock within viaIR's stack budget.
    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events,calls-loop
    function _settleCancel(address payee,uint256 index) internal {
        address lp=locks[payee][index].payer;
        address lt=locks[payee][index].token;
        uint256 lj=locks[payee][index].jobId;
        uint256 la=locks[payee][index].amount; // gross L
        bytes32 lid=_lockId(payee,lp,lj);
        uint256 S=sponsorships[lid].total;
        uint256 P=la-S; // payer-funded portion
        //update auths (only P was tracked)
        _releasePayerLocked(lp,lt,payee,P);
        //return the payer-funded portion to the payer (NOT the gross amount)
        funds[lp][lt].available+=P;
        funds[lp][lt].locked-=P;
        emit Canceled(payee,lj,lt,lp,la);
        //refund the full sponsored portion to providers (consume=0 -> full refund; library clears entry)
        if(S>0){
            SponsorshipLib.settleRefund(sponsorships,sponsoredTotal,providerReclaimable,lid,payee,lp,lj,lt,0);
        }
    }

    // slither-disable-next-line reentrancy-eth,reentrancy-benign,reentrancy-events,calls-loop
    function _cancelExpiredLock(uint256 jobId,address token,address payer,address payee) internal{
        require(payee!=address(0),'Invalid payee');
        uint256 index;
        //since solidy does not supports dynamic arrays, we need to count first
        uint256 found=0;
        uint256 length=locks[payee].length;
        for(index=0;index<length;index++){
            if(locks[payee][index].expiry<block.timestamp &&
                (
                    (jobId==0 || jobId==locks[payee][index].jobId) &&
                    (token==address(0) || token==locks[payee][index].token) &&
                    (payer==address(0) || payer==locks[payee][index].payer)
                )
            ){
                found++;
            }
        }
        // bail out if we don't have any expired matching locks
        if(found==0) return;
        uint256[] memory indexToDelete=new uint256[](found);
        uint256 currentIndex=0;
        // now actually do the work
        for(index=0;index<length;index++){
            if(locks[payee][index].expiry<block.timestamp &&
                (
                    (jobId==0 || jobId==locks[payee][index].jobId) &&
                    (token==address(0) || token==locks[payee][index].token) &&
                    (payer==address(0) || payer==locks[payee][index].payer)
                )
            ){
                //cancel each lock, one by one, keyed by the matched lock's OWN payer/jobId/token
                _settleCancel(payee,index);
                indexToDelete[currentIndex]=index;
                currentIndex++;
            }
        }
        //delete the locks
        uint256 delLength=indexToDelete.length;
        // Sort indexToDelete in descending order
        for (uint256 i = 0; i < delLength - 1; i++) {
            for (uint256 j = i + 1; j < delLength; j++) {
                if (indexToDelete[i] < indexToDelete[j]) {
                    uint256 temp = indexToDelete[i];
                    indexToDelete[i] = indexToDelete[j];
                    indexToDelete[j] = temp;
                }
            }
        }
        // Delete the locks safely
        for (index = 0; index < delLength; index++) {
            uint256 delIndex = indexToDelete[index];
            if (delIndex < locks[payee].length - 1) {
                locks[payee][delIndex] = locks[payee][locks[payee].length - 1];
            }
            locks[payee].pop();
        }
    }

    /* Lock-time sponsorship: provider reclaim + views + capability discovery */

    /**
     * @dev sweepReclaimable
     *      A provider withdraws tokens parked in its reclaimable bucket (refunds whose push failed).
     *      CEI: zero the bucket BEFORE transferring.
     * @param token token to sweep
     */
    function sweepReclaimable(address token) external nonReentrant{
        uint256 amount=providerReclaimable[msg.sender][token];
        require(amount>0,"Invalid amount"); // nothing to sweep
        providerReclaimable[msg.sender][token]=0; // zero before transfer (CEI)
        IERC20(token).safeTransfer(msg.sender,amount);
    }

    /// @notice Total sponsored tokens of `token` currently held in the non-withdrawable bucket.
    function getSponsoredTotal(address token) external view returns (uint256){
        return sponsoredTotal[token];
    }

    /// @notice Max UNIQUE sponsors a lock may have (createLock/reLock revert beyond it). Single source of
    ///         truth is SponsorshipLib; exposed so ocean-node / ocean.js can cap their provider lists.
    function maxSponsorsPerLock() external pure returns (uint256){
        return SponsorshipLib.MAX_SPONSORS;
    }

    /// @notice Amount of `token` parked for `provider` after a failed refund push.
    function getReclaimable(address provider,address token) external view returns (uint256){
        return providerReclaimable[provider][token];
    }

    /// @notice The sponsorship backing a lock, keyed by (payee, payer, jobId).
    function getSponsorship(address payee,address payer,uint256 jobId) external view
        returns (uint256 total,address[] memory providers,uint256[] memory amounts){
        SponsorshipLib.Sponsorship storage sp=sponsorships[_lockId(payee,payer,jobId)];
        return (sp.total,sp.providers,sp.amounts);
    }

    /// @notice Cosmetic label distinguishing community vs enterprise deployments.
    function escrowKind() external pure returns (EscrowKind){
        return EscrowKind.ENTERPRISE;
    }

    /// @notice Escrow ABI/feature revision.
    function version() external pure returns (uint16){
        return 2;
    }

    /// @notice ERC-165 capability discovery.
    function supportsInterface(bytes4 interfaceId) external pure returns (bool){
        return interfaceId==type(IERC165).interfaceId
            || interfaceId==type(IEscrowCore).interfaceId
            || interfaceId==type(IEscrowLockSubsidy).interfaceId
            || interfaceId==type(IEscrowEnterprise).interfaceId;
    }

    /* IEscrowEnterprise: read-only passthroughs so integrators can check token eligibility / preview the
       enterprise fee BEFORE createLock (which reverts on a disallowed token or fee>=amount). Mirror
       _requireEnterpriseFee's semantics exactly, including the "no collector => no gate" case. */

    /// @notice the IEnterpriseFeeCollector this escrow uses (== opcCollector); address(0) => no gate.
    function feeCollector() external view returns (address){
        return opcCollector;
    }

    /// @notice whether `token` is usable for locks here (true when no fee collector is set).
    function isTokenAllowed(address token) external view returns (bool){
        if(opcCollector==address(0)) return true;
        return IEnterpriseFeeCollector(opcCollector).isTokenAllowed(token);
    }

    /// @notice the enterprise fee charged on `amount` of `token` (0 when no collector is set);
    ///         createLock requires it to be strictly less than `amount`.
    function previewFee(address token,uint256 amount) external view returns (uint256){
        if(opcCollector==address(0)) return 0;
        return IEnterpriseFeeCollector(opcCollector).calculateFee(token,amount);
    }
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

@openzeppelin/contracts/utils/math/SafeMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

contracts/escrow/SponsorshipLib.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/ISubsidyLockProvider.sol";

/**
 * @title SponsorshipLib
 * @dev Lock-time ("pre-funded") sponsorship engine for the Ocean escrows, factored into an EXTERNAL
 *      (delegatecall-linked) library so most of the provider-interaction bytecode lives once outside each
 *      escrow (EIP-170 headroom — audit risk #5). The library's external functions are DELEGATECALLed by
 *      the escrow, so they execute in the ESCROW's storage/identity context:
 *        - storage mapping parameters (sponsorships / sponsoredTotal / providerReclaimable) resolve to the
 *          escrow's own slots (the escrow declares them; the library only receives references),
 *        - `address(this)` is the escrow, so `token.transferFrom(provider, address(this), …)` pulls to the
 *          escrow and `token.transfer(provider, …)` pushes from the escrow balance,
 *        - a CALL made here to a provider carries `msg.sender == address(this) == escrow` (the provider's
 *          `require(msg.sender == authorizedEscrow)` passes),
 *        - events emitted here are attributed to the escrow address (same topic as IEscrowLockSubsidy).
 *      Behaviour is byte-identical to the previously in-escrow helpers.
 */
library SponsorshipLib {
    // The sponsorship backing a lock, keyed in the escrow by keccak256(abi.encode(payee, payer, jobId)).
    struct Sponsorship { uint256 total; uint256 jobType; address[] providers; uint256[] amounts; }

    // Same signatures as IEscrowLockSubsidy; under delegatecall they log against the escrow address.
    event LockSponsored(address indexed payer,address indexed payee,uint256 jobId,address token,address provider,uint256 amount);
    event SponsorRefunded(address indexed payer,address indexed payee,uint256 jobId,address token,address provider,uint256 amount,bool reclaimable);

    // gas forwarded to the (revert-swallowed) onSubsidyRefund notify; bounds griefing in the
    // permissionless cancel batch while leaving room for the provider's budget bookkeeping.
    uint256 private constant REFUND_NOTIFY_GAS = 120000;
    // gas forwarded to the refund PUSH transfer; generous for any standard ERC20 but caps a
    // callback/ERC-777-token gas-bomb so it cannot OOG-brick a claim or the permissionless cancel
    // batch (on OOG/revert the amount falls through to providerReclaimable, recoverable via sweep).
    uint256 private constant REFUND_PUSH_GAS = 100000;
    // hard cap on UNIQUE sponsors per lock. settleRefund / shrinkSponsored loop over every recorded
    // provider doing an external push + notify each, so an unbounded set (many tiny sponsors, or
    // accreted across reLock-grows) could push claim/cancel over the block gas limit and brick
    // settlement. createLock / reLock REVERT when a new sponsor would exceed this; already-recorded
    // sponsors may still accumulate. `internal` so each escrow can expose it (maxSponsorsPerLock()) —
    // single source of truth for ocean-node / ocean.js.
    uint256 internal constant MAX_SPONSORS = 10;

    /* ===================== external (delegatecall-linked) ===================== */

    /**
     * @dev createLock / reLock-grow. Consults each UNIQUE non-payer provider for up-front sponsorship of
     *      `lockAmount`; `remaining` starts at `lockAmount` and decrements; each provider is capped at
     *      min(grant, remaining) then pulled reject-partial. Contributions are merged by provider address
     *      into sponsorships[lockId] (so a repeat provider on reLock-grow accumulates), and the newly
     *      sponsored amount is added to sponsorship.total, sponsorship.jobType and sponsoredTotal[token].
     *      At most MAX_SPONSORS UNIQUE providers are recorded per lock (the settlement loops are O(providers));
     *      a call that would record a NEW provider beyond the cap REVERTS ("Too many sponsors").
     *      One bad provider/token never reverts the lock (low-level quote, reject-partial pull).
     * @return added newly sponsored amount (S on create, S_add on grow); <= lockAmount by the cap.
     */
    function applyLockSubsidies(
        mapping(bytes32 => Sponsorship) storage sponsorships,
        mapping(address => uint256) storage sponsoredTotal,
        uint256 jobId,
        bytes32 lockId,
        address node,
        address payer,
        address token,
        uint256 jobType,
        uint256 lockAmount,
        address[] memory providers
    ) external returns (uint256 added) {
        Sponsorship storage sp = sponsorships[lockId];
        uint256 remaining = lockAmount;
        for (uint256 i = 0; i < providers.length; i++) {
            if (remaining == 0) break;
            address provider = providers[i];
            if (provider == payer) continue;
            if (_seen(providers, i, provider)) continue; // no stacked grants from a repeated entry
            uint256 want = _consult(lockId, node, payer, token, jobType, lockAmount, provider, remaining);
            if (want == 0) continue;
            // cap UNIQUE sponsors per lock: REJECT (revert) a new contributing sponsor beyond the limit so
            // the settlement loops stay bounded. An already-recorded sponsor may still accumulate, so a
            // reLock-grow on existing sponsors keeps working at the cap. (The reverting pull rolls back.)
            require(_recorded(sp, provider) || sp.providers.length < MAX_SPONSORS, "Too many sponsors");
            _record(sp, provider, want); // merge by address
            added += want;
            remaining -= want;
            emit LockSponsored(payer, node, jobId, token, provider, want);
        }
        if (added > 0) {
            sp.total += added;
            sp.jobType = jobType;
            sponsoredTotal[token] += added;
        }
    }

    /**
     * @dev claim / cancel full settlement. Consume `consume` from the stored amounts in LIST ORDER
     *      (exact, no division), refund each provider its unused remainder amt_i - consumed_i (push +
     *      reclaimable fallback + revert-swallowing onSubsidyRefund notify), then decrement
     *      sponsoredTotal by the whole total and delete the sponsorship entry.
     *      consume = fromSponsored (claim, amount C <= L) or 0 (cancel -> full refund).
     */
    function settleRefund(
        mapping(bytes32 => Sponsorship) storage sponsorships,
        mapping(address => uint256) storage sponsoredTotal,
        mapping(address => mapping(address => uint256)) storage providerReclaimable,
        bytes32 lockId,
        address payee,
        address payer,
        uint256 jobId,
        address token,
        uint256 consume
    ) external {
        Sponsorship storage sp = sponsorships[lockId];
        uint256 jobType = sp.jobType;
        uint256 total = sp.total;
        uint256 np = sp.providers.length;
        // EFFECTS first (CEI): snapshot providers + per-provider refunds, then clear state, THEN push.
        address[] memory provs = new address[](np);
        uint256[] memory refs = new uint256[](np);
        uint256 rem = consume;
        for (uint256 i = 0; i < np; i++) {
            uint256 amt = sp.amounts[i];
            uint256 c = amt < rem ? amt : rem;
            rem -= c;
            provs[i] = sp.providers[i];
            refs[i] = amt - c;
        }
        sponsoredTotal[token] -= total;
        delete sponsorships[lockId];
        // INTERACTIONS last
        for (uint256 i = 0; i < np; i++) {
            if (refs[i] > 0) _refundOne(providerReclaimable, lockId, provs[i], payee, payer, jobId, jobType, token, refs[i]);
        }
    }

    /**
     * @dev reLock-shrink. Refund the sponsored reduction d = S_old - S_new IN LIST ORDER
     *      (refund_i = min(amt_i, remaining_d) walking providers — NOT per-provider flooring, which can
     *      over-assign the last provider), reduce each provider's stored amount, decrement sponsoredTotal
     *      by d, and set total = S_new (or delete the entry when S_new == 0).
     */
    function shrinkSponsored(
        mapping(bytes32 => Sponsorship) storage sponsorships,
        mapping(address => uint256) storage sponsoredTotal,
        mapping(address => mapping(address => uint256)) storage providerReclaimable,
        bytes32 lockId,
        address payee,
        address payer,
        uint256 jobId,
        address token,
        uint256 S_old,
        uint256 S_new
    ) external {
        uint256 d = S_old - S_new;
        Sponsorship storage sp = sponsorships[lockId];
        uint256 jobType = sp.jobType;
        uint256 np = sp.providers.length;
        // EFFECTS first (CEI): snapshot providers + per-provider refunds and apply all state, THEN push.
        address[] memory provs = new address[](np);
        uint256[] memory refs = new uint256[](np);
        uint256 remD = d;
        for (uint256 i = 0; i < np; i++) {
            uint256 amt = sp.amounts[i];
            uint256 r = amt < remD ? amt : remD;
            remD -= r;
            provs[i] = sp.providers[i];
            refs[i] = r;
            if (r > 0) sp.amounts[i] = amt - r; // keep stored amounts consistent with S_new
        }
        sponsoredTotal[token] -= d;
        if (S_new == 0) { delete sponsorships[lockId]; }
        else { sp.total = S_new; }
        // INTERACTIONS last
        for (uint256 i = 0; i < np; i++) {
            if (refs[i] > 0) _refundOne(providerReclaimable, lockId, provs[i], payee, payer, jobId, jobType, token, refs[i]);
        }
    }

    /* ===================== internal helpers (embedded in the library) ===================== */

    // true if `provider` appears in list[0..upto)
    function _seen(address[] memory list, uint256 upto, address provider) private pure returns (bool) {
        for (uint256 j = 0; j < upto; j++) { if (list[j] == provider) return true; }
        return false;
    }

    // true if `provider` is already a recorded sponsor of this lock (used by the MAX_SPONSORS cap so an
    // existing sponsor can keep accumulating while a new one is dropped at the limit)
    function _recorded(Sponsorship storage sp, address provider) private view returns (bool) {
        uint256 plen = sp.providers.length;
        for (uint256 k = 0; k < plen; k++) { if (sp.providers[k] == provider) return true; }
        return false;
    }

    // record `want` for `provider`, merging into its existing slot by address (reLock-grow accumulates)
    function _record(Sponsorship storage sp, address provider, uint256 want) private {
        uint256 plen = sp.providers.length;
        for (uint256 k = 0; k < plen; k++) {
            if (sp.providers[k] == provider) { sp.amounts[k] += want; return; }
        }
        sp.providers.push(provider);
        sp.amounts.push(want);
    }

    // LOW-LEVEL onSubsidyLock quote (failed call OR <32-byte returndata contributes 0), cap at
    // `remaining`, then a reject-partial pull. Returns the accepted amount.
    function _consult(bytes32 lockId, address node, address payer, address token, uint256 jobType,
        uint256 lockAmount, address provider, uint256 remaining) private returns (uint256 want) {
        if (provider.code.length == 0) return 0;
        (bool ok, bytes memory data) = provider.call(
            abi.encodeWithSelector(ISubsidyLockProvider.onSubsidyLock.selector,
                lockId, node, payer, jobType, token, lockAmount, remaining));
        if (!ok || data.length < 32) return 0;
        uint256 sponsorAmount = abi.decode(data, (uint256));
        want = sponsorAmount < remaining ? sponsorAmount : remaining; // cap
        if (want == 0) return 0;
        if (!_pull(token, provider, want)) return 0; // reject-partial
        return want;
    }

    // guarded token pull: low-level transferFrom(provider -> escrow); balanceOf-diff is the sole source
    // of truth; returns true only if the escrow received the FULL `want` (reject-partial). address(this)
    // is the escrow under delegatecall, so tokens land in the escrow.
    function _pull(address token, address provider, uint256 want) private returns (bool) {
        uint256 b = IERC20(token).balanceOf(address(this));
        (bool ok,) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, provider, address(this), want));
        if (!ok) return false;
        uint256 a = IERC20(token).balanceOf(address(this));
        return (a >= b ? a - b : 0) >= want;
    }

    // PUSH one provider's refund via a guarded low-level transfer (never safeTransfer — a reverting /
    // blacklisting token must not brick the claim or the permissionless cancel batch); on failure credit
    // providerReclaimable. Then notify onSubsidyRefund (revert-swallowing, gas-bounded) so the provider
    // can restore its budget — called in BOTH branches (budget restored regardless of push success).
    function _refundOne(
        mapping(address => mapping(address => uint256)) storage providerReclaimable,
        bytes32 lockId,
        address provider,
        address payee,
        address payer,
        uint256 jobId,
        uint256 jobType,
        address token,
        uint256 refund
    ) private {
        uint256 b = IERC20(token).balanceOf(address(this));
        (bool ok,) = token.call{gas: REFUND_PUSH_GAS}(abi.encodeWithSelector(IERC20.transfer.selector, provider, refund));
        uint256 a = IERC20(token).balanceOf(address(this));
        bool dropped = b >= a && (b - a) >= refund;
        if (!ok || !dropped) {
            providerReclaimable[provider][token] += refund;
            emit SponsorRefunded(payer, payee, jobId, token, provider, refund, true);
        } else {
            emit SponsorRefunded(payer, payee, jobId, token, provider, refund, false);
        }
        provider.call{gas: REFUND_NOTIFY_GAS}(abi.encodeWithSelector(
            ISubsidyLockProvider.onSubsidyRefund.selector, lockId, payee, payer, jobType, token, refund));
    }
}

contracts/interfaces/IEnterpriseFeeCollector.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

interface IEnterpriseFeeCollector {
    function calculateFee(
        address baseTokenAddress,
        uint256 amount
    ) external view returns (uint256);
    function isTokenAllowed(address tokenAddress) 
        external 
        view 
        returns (bool);
}

contracts/interfaces/IEscrowCore.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

/**
 * @title IEscrowCore
 * @dev ERC-165 capability MARKER for the Ocean escrow's base surface at the v2 (major) signatures:
 *      `createLock`/`reLock` carry `jobType` + `subsidyProviders` (like `claimLock`), and `authorize`
 *      carries an `expiryTimestamp`. A contract advertises support via
 *      `supportsInterface(type(IEscrowCore).interfaceId)`; discovery callers treat a failed/absent
 *      staticcall as "legacy, assume base-only", never a revert.
 *
 *      This interface is consumed for its `interfaceId` and as documentation of the surface; the escrow
 *      declares support in `supportsInterface` without necessarily inheriting it. Keep it FROZEN once
 *      shipped — new capabilities get their own `IEscrow*` marker, never a change here.
 */
interface IEscrowCore {
    function deposit(address token, uint256 amount) external;

    function withdraw(address[] calldata token, uint256[] calldata amount) external;

    function authorize(
        address token,
        address payee,
        uint256 maxLockedAmount,
        uint256 maxLockSeconds,
        uint256 maxLockCounts,
        uint256 expiryTimestamp
    ) external;

    function createLock(
        uint256 jobId,
        address token,
        address payer,
        uint256 amount,
        uint256 expiry,
        uint256 jobType,
        address[] calldata subsidyProviders
    ) external;

    function reLock(
        uint256 jobId,
        address token,
        address payer,
        uint256 amount,
        uint256 expiry,
        uint256 jobType,
        address[] calldata subsidyProviders
    ) external;

    function claimLock(
        uint256 jobId,
        address token,
        address payer,
        uint256 amount,
        bytes calldata proof,
        uint256 jobType,
        address[] calldata subsidyProviders
    ) external;

    function cancelExpiredLock(
        uint256 jobId,
        address token,
        address payer,
        address payee
    ) external;
}

contracts/interfaces/IEscrowEnterprise.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

/**
 * @title IEscrowEnterprise
 * @dev ERC-165 capability interface for the ENTERPRISE escrow flavour, which (unlike the community
 *      `Escrow`) restricts which tokens are usable and charges a configurable enterprise fee via its
 *      `IEnterpriseFeeCollector`. These read-only passthroughs let an integrator check token
 *      eligibility and preview the fee BEFORE calling `createLock` (which otherwise reverts on a
 *      disallowed token or a fee >= amount). Discover with
 *      `supportsInterface(type(IEscrowEnterprise).interfaceId)`; only the enterprise escrow advertises it.
 *      Use `escrowKind()` for the community-vs-enterprise label itself.
 *
 *      When the escrow has no fee collector configured (`feeCollector() == address(0)`) there is no gate:
 *      `isTokenAllowed` returns true for any token and `previewFee` returns 0.
 */
interface IEscrowEnterprise {
    /// @notice the IEnterpriseFeeCollector this escrow uses (== opcCollector); address(0) means no gate.
    function feeCollector() external view returns (address);

    /// @notice whether `token` is usable for locks here — mirrors the createLock token gate exactly
    ///         (true when no fee collector is set).
    function isTokenAllowed(address token) external view returns (bool);

    /// @notice the enterprise fee that would be charged on `amount` of `token` (0 when no collector is
    ///         set). createLock requires this to be strictly less than `amount`.
    function previewFee(address token, uint256 amount) external view returns (uint256);
}

contracts/interfaces/IEscrowLockSubsidy.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

/**
 * @title IEscrowLockSubsidy
 * @dev ERC-165 capability MARKER for the escrow's lock-time ("pre-funded") sponsorship surface. Present
 *      only on deployments that ship the feature; discover via
 *      `supportsInterface(type(IEscrowLockSubsidy).interfaceId)`. Consumed for its `interfaceId` and as
 *      documentation; keep FROZEN once shipped.
 */
interface IEscrowLockSubsidy {
    /// emitted once per provider that pre-funds part of a lock (at createLock / reLock-grow).
    event LockSponsored(
        address indexed payer,
        address indexed payee,
        uint256 jobId,
        address token,
        address provider,
        uint256 amount
    );

    /// emitted once per provider when unused sponsored tokens are returned (partial claim / expiry /
    /// reLock-shrink). `reclaimable == true` means the push failed and the amount was credited to the
    /// provider's reclaimable bucket instead of transferred.
    event SponsorRefunded(
        address indexed payer,
        address indexed payee,
        uint256 jobId,
        address token,
        address provider,
        uint256 amount,
        bool reclaimable
    );

    /// @notice Max UNIQUE sponsors a single lock may have; createLock/reLock revert ("Too many sponsors")
    ///         when a new sponsor would exceed it. Read it so clients can cap their provider list.
    function maxSponsorsPerLock() external view returns (uint256);

    /// @notice A provider withdraws tokens parked in its reclaimable bucket (a refund whose push failed).
    function sweepReclaimable(address token) external;

    /// @notice Total sponsored tokens of `token` currently held in the non-withdrawable bucket.
    function getSponsoredTotal(address token) external view returns (uint256);

    /// @notice Amount of `token` parked for `provider` after a failed refund push.
    function getReclaimable(address provider, address token) external view returns (uint256);

    /// @notice The sponsorship backing a lock, keyed by (payee, payer, jobId).
    /// @return total sum currently sponsored for the lock.
    /// @return providers the contributing providers.
    /// @return amounts each provider's current contribution (parallel to `providers`).
    function getSponsorship(
        address payee,
        address payer,
        uint256 jobId
    ) external view returns (uint256 total, address[] memory providers, uint256[] memory amounts);
}

contracts/interfaces/ISubsidyLockProvider.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

/**
 * @title ISubsidyLockProvider
 * @dev Lock-time ("pre-funded") sponsorship, a SEPARATE interface from `ISubsidyProvider` so that
 *      adding it never changes `type(ISubsidyProvider).interfaceId` (the ERC-165 marker of the shipped
 *      claim-time interface stays frozen). A provider may implement one or both; the escrow discovers
 *      lock-time support by calling `onSubsidyLock` with a LOW-LEVEL call (a non-implementing provider
 *      contributes 0, never reverts the lock).
 *
 *      MODEL. Unlike `onSubsidyClaim` (reimbursement: the subsidy is released to the PAYER AFTER the
 *      claim), lock-time sponsorship PRE-FUNDS the lock: the escrow pulls the provider's tokens into a
 *      non-withdrawable bucket when the lock is created, and the node is later paid from that bucket
 *      first. A fully-sponsored payer can therefore transact with ZERO deposit. Unused sponsored tokens
 *      (partial claim / expiry / reLock-shrink) are PUSHED back to the provider by the escrow, which
 *      then calls `onSubsidyRefund` so the provider can restore its budget.
 *
 *      RESERVATION ACCOUNTING (why `lockId`). `onSubsidyLock` reserves budget against the CURRENT
 *      window (e.g. a rolling day/week/month counter, or a one-time round). A lock can live up to the
 *      authorization's maxLockSeconds and routinely crosses a window boundary (or an admin round bump)
 *      before the refund arrives. The refund therefore MUST reverse the EXACT counters that were
 *      debited at lock time, not whatever window is current at refund time — otherwise the budget
 *      underflows (silent subsidy leak / DoS) or credits a window it never debited (cap bypass). The
 *      escrow passes a stable `lockId` to both callbacks; the provider records the reserved slots keyed
 *      by `lockId` at lock and reverses them on refund.
 */
interface ISubsidyLockProvider {
    /// @notice Called by the escrow inside `createLock` (and `reLock`-grow) for each named provider.
    /// @param lockId stable id of the lock = keccak256(abi.encode(payee, payer, jobId)); the provider
    ///        keys its per-lock reservation by this value. On a reLock-grow the SAME lockId is passed
    ///        again, so the provider ADDS to the existing reservation.
    /// @param node   payee / msg.sender of the lock.
    /// @param payer  the user the lock is created for.
    /// @param jobType opaque category supplied by the node.
    /// @param token  the lock token.
    /// @param lockAmount the bonus/pct sizing basis: the full (gross) lock amount on `createLock`, but on
    ///        a `reLock`-grow only the GROWTH DELTA (new total − old total), since sponsorship is applied
    ///        to the added portion only.
    /// @param sponsorNeeded remaining amount still unsponsored by earlier providers in this lock's list.
    ///        The escrow caps the pulled amount at this value and refunds (at partial claim / expiry /
    ///        reLock-shrink) only what it actually pulled, so any excess above `sponsorNeeded` is NEITHER
    ///        pulled NOR ever refunded. A provider MUST therefore cap its returned `sponsorAmount`, its
    ///        budget debit, and its `lockId` reservation at `sponsorNeeded`; over-returning silently
    ///        leaks the provider's own budget (debited but never pulled, so never credited back).
    /// @return sponsorAmount amount of `token` the provider funds up-front (MUST be <= sponsorNeeded, see
    ///         above). The provider decrements a PERSISTED budget by this amount, records the reservation
    ///         under `lockId`, and approves the escrow (msg.sender) to pull exactly `sponsorAmount`
    ///         just-in-time (`IERC20(token).approve(msg.sender, sponsorAmount)`), which the escrow pulls
    ///         immediately (reject-partial).
    ///
    /// SECURITY — like `onSubsidyClaim`, a correct implementation MUST (a) require(msg.sender == a
    /// registered escrow), (b) authenticate node/payer/jobType via its gates, and (c) persist the
    /// reservation BEFORE the approve. In addition, because sponsored tokens are paid straight to the
    /// NODE at claim (no payer deposit fronted), a provider offering this leg SHOULD require a
    /// nodeAccessList (and realistically a userAccessList): with open gates it is drainable by a sybil
    /// node + disposable payers.
    function onSubsidyLock(
        bytes32 lockId,
        address node,
        address payer,
        uint256 jobType,
        address token,
        uint256 lockAmount,
        uint256 sponsorNeeded
    ) external returns (uint256 sponsorAmount);

    /// @notice Called by the escrow AFTER it has already pushed `refundAmount` of `token` back to the
    ///         provider (partial claim / expiry / reLock-shrink). This call does NOT move tokens; it
    ///         only lets the provider restore its budget by crediting back the EXACT window counters it
    ///         debited at lock, looked up by `lockId`. May be called multiple times per `lockId`
    ///         (partial refunds); the sum never exceeds the amount reserved under that `lockId`.
    ///
    /// SECURITY — MUST require(msg.sender == the registered escrow). Must be tolerant: the escrow calls
    /// it with a low-level, revert-swallowing call, so a revert here only forfeits the budget credit
    /// (the tokens were already returned); it must not assume a token pull.
    function onSubsidyRefund(
        bytes32 lockId,
        address node,
        address payer,
        uint256 jobType,
        address token,
        uint256 refundAmount
    ) external;
}

contracts/interfaces/ISubsidyProvider.sol

pragma solidity 0.8.12;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

/**
 * @title ISubsidyProvider
 * @dev Interface a third party implements to sponsor part of a payer's claim cost (a
 *      `subsidyAmount`, released back to the payer) and/or to add an extra reward on top for the
 *      node (a `bonusAmount`, paid to the payee/node). The escrow calls `onSubsidyClaim` once per
 *      entry of the node-supplied provider list, inside the claim transaction.
 */
interface ISubsidyProvider {
    /// @param node   payee / msg.sender of the claim
    /// @param payer  the user whose lock is being claimed
    /// @param jobType opaque category supplied by the node (the escrow never interprets it)
    /// @param token  the lock token
    /// @param amount full claim amount (bonus basis)
    /// @param subsidyNeeded remaining subsidy still uncovered by earlier providers in this claim's
    ///        list; it starts at `amount` and decreases as providers subsidize, and is **0** once
    ///        the job is already fully subsidized. A provider should offer at most `subsidyNeeded`
    ///        of subsidy, but may still return a `bonusAmount` even when `subsidyNeeded == 0`.
    ///        `amount` is always the full claim amount, so a provider can size its bonus as, e.g., a
    ///        percentage of the job regardless of how much subsidy is left.
    /// @return subsidyAmount amount of `token` that covers part of the PAYER's cost (released back to
    ///         the payer; escrow caps it at the remaining un-subsidized portion of the claim).
    /// @return bonusAmount   amount of `token` paid as an EXTRA reward to the NODE, on top of the
    ///         claim amount (not released to the payer; uncapped).
    ///
    /// Inside this call the provider updates its own budget/state AND approves the escrow to pull
    /// `subsidyAmount + bonusAmount` just-in-time, i.e.
    /// `IERC20(token).approve(msg.sender /* escrow */, subsidyAmount + bonusAmount)`
    /// (msg.sender of this callback is the escrow contract). Immediately after this returns, the
    /// escrow pulls the tokens with `transferFrom(provider -> escrow)` and never pulls more than the
    /// (capped subsidy + bonus) it can actually receive.
    ///
    /// SECURITY - a correct provider implementation MUST do ALL of the following, or it is drainable:
    ///   (a) `require(msg.sender == <the escrow address>)` - otherwise an attacker calls this
    ///       function directly with a spoofed `node`/`payer`, gets the just-in-time `approve`, and
    ///       `transferFrom`s the funds with no real claim at all.
    ///   (b) authenticate `node` / `payer` / `jobType` and only fund combinations it intends to.
    ///   (c) decrement a PERSISTED budget per call - the escrow calls this ONCE PER LIST ENTRY, and a
    ///       node may list the same provider many times in one claim, so a fixed per-call amount with
    ///       no persisted budget is drained Nx in a single transaction.
    /// The escrow calls the provider on a node-chosen address and `bonusAmount` is uncapped, so a
    /// provider missing any of (a)-(c) can be drained up to its escrow allowance. The escrow itself
    /// stays solvent regardless; this is the provider's own risk.
    ///
    /// RESIDUAL EXPOSURE - the escrow only enforces `provider != payer` and a "typed call, skip on
    /// revert" pattern. Any *third-party* smart-account that (i) holds a standing escrow allowance and
    /// (ii) returns two non-zero uints from a bare `onSubsidyClaim`/fallback can still be pulled from
    /// when a node names it as a provider. Integrators with permissive smart-account wallets are
    /// warned: do NOT keep a standing escrow allowance on a wallet whose fallback returns data.
    function onSubsidyClaim(
        address node,
        address payer,
        uint256 jobType,
        address token,
        uint256 amount,
        uint256 subsidyNeeded
    ) external returns (uint256 subsidyAmount, uint256 bonusAmount);
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {
    "contracts/escrow/EnterpriseEscrow.sol": {
      "SponsorshipLib": "0x9a560d472c08c8a69dc131ae56f40b0b011f551e"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.