Verified contractExactUNLICENSED
OLinxVault
Address0x17613847cbbcc8eae96b3245a27a8f87d677b1dd
- Balance
0.0029 ETH
- Transactions
14
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,303,952
- Creation transaction
- 0xfb0cea0876…01243ae21a
6 files
- project/contracts/vault/v1/OLinxVault.solmain27.59 KB
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.77 KB
- npm/@openzeppelin/[email protected]/token/ERC20/extensions/draft-IERC20Permit.sol2.25 KB
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol4.46 KB
- npm/@openzeppelin/[email protected]/utils/Address.sol8.31 KB
- project/contracts/vault/v1/IOLinxVault.sol6.33 KB
project/contracts/vault/v1/OLinxVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IOLinxVault.sol";
// The OLinx vault of one network (requirements v10.0). It never changes: no upgrade, no owner of its code. It holds
// the money of every order and every take's payment on its network and is the only creator of their NFTs and
// receipts. It knows money, not trading: the trading rules are versions beside it, and each entry keeps its version
// for life. A version can only ask the vault to pay out its own entries, never more than they hold, and the vault
// takes coins only from the wallet that calls it, never more than that call allows.
//
// An order's holder can always cancel it here, under any version in any state, and no version is asked (VA05); the
// holder may also move it to another version, or to a later vault the control contract allows (VA13, VA31).
//
// Who decides, and when, is the control contract's (OLinxControl): the admin, the guardian, the waiting times and the
// queue. It approves versions, sets their dates, pauses, lists tokens, sets limits and the NFTs' descriptions, and
// names the vaults orders may move to. It can never move anyone's money: nothing here lets it.
contract OLinxVault is IOLinxVault {
using SafeERC20 for IERC20;
struct Version {
bytes32 family;
uint8 state;
// From this time the version is retired: no takes, no fills, no new orders. Zero: no closing date.
uint64 closingDate;
uint64 pausedUntil;
}
// Version states. A closed version takes no new orders (from when the next one of its family opened); its orders
// can still be taken until its closing date.
uint8 public constant APPROVED_OPEN = 1;
uint8 public constant CLOSED = 2;
uint8 public constant LISTED = 1;
uint8 public constant STOPPED = 2;
// How an entry ended (Closed events).
uint8 public constant ENDED_BY_VERSION = 1;
uint8 public constant CANCELLED = 2;
uint8 public constant MOVED = 3;
uint8 public constant RELEASED = 4;
uint8 public constant MOVED_OUT = 5;
// The network's coin is sent with this much gas; a receiver that needs more claims it.
uint256 private constant PUSH_GAS = 30000;
uint8 private constant FREE = 1;
uint8 private constant BUSY = 2;
address public immutable override control;
IOLinxVaultOrders public immutable override orders;
IOLinxVaultReceipts public immutable override receipts;
address public immutable wrapped;
address private bootstrap;
bool public initialized;
mapping(address => Version) private versions;
mapping(bytes32 => address) public openVersion;
mapping(address => uint8) public tokenStatus;
mapping(bytes32 => VaultEntry) private entries;
// What each version's entries hold of each token, its ceiling and its daily payout limit (zero: none).
mapping(address => mapping(address => uint256)) public held;
mapping(address => mapping(address => uint256)) public ceiling;
mapping(address => mapping(address => uint256)) public dailyLimit;
mapping(address => mapping(address => mapping(uint256 => uint256))) public paidOnDay;
// Payouts their receiver could not take: the network's coin, and tokens (token => owner => amount).
mapping(address => uint256) public owed;
mapping(address => mapping(address => uint256)) public tokensOwed;
// The later vaults an order may be moved to (VA31).
mapping(address => bool) public destination;
// One lock for the whole vault, and the call of a version in progress.
uint8 private status = FREE;
address private callVersion;
address private callCaller;
address private callCoin;
bool private callWrap;
bool private callMove;
// How much more of the call's coin may come in: from the caller's wallet, from the coin sent (wrapped), or in a
// move from the moved order (already here). And what is left of the network's coin the call may use.
uint256 private callLeft;
uint256 private callNative;
event VersionApproved(address indexed version, bytes32 indexed family, address closed);
event ClosingDateSet(address indexed version, uint64 date);
event Paused(address indexed version, uint64 until);
event TokenStatusSet(address indexed token, uint8 status);
event LimitsSet(address indexed version, address indexed token, uint256 ceiling, uint256 dailyLimit);
event DestinationSet(address indexed vault, bool allowed);
event Opened(bytes32 indexed id, address indexed version, address indexed holder, uint8 kind, address token, uint256 amount, uint256 deposit, uint64 releaseAt);
event Paid(bytes32 indexed id, address indexed to, uint256 amount, bool held);
event DepositPaid(bytes32 indexed id, address indexed to, uint256 amount, bool held);
event Collected(address indexed version, address indexed from, address indexed to, address token, uint256 amount);
event Forwarded(address indexed version, address indexed to, uint256 amount, bool held);
event Converted(bytes32 indexed lockId, bytes32 indexed orderId, uint256 amount);
event Closed(bytes32 indexed id, address indexed holder, uint256 returned, uint256 deposit, uint8 how);
event Returned(address indexed to, address token, uint256 amount, uint256 native);
event Claimed(address indexed owner, address indexed token, uint256 amount);
// A payout the vault keeps for its owner because it could not be sent (token 0: the network's own coin), so
// every held payout is on the chain as its own event, a held return as much as a held payment.
event Held(address indexed owner, address indexed token, uint256 amount);
constructor(address control_, IOLinxVaultOrders orders_, IOLinxVaultReceipts receipts_, address wrapped_) {
require(control_.code.length > 0 && address(orders_).code.length > 0 && address(receipts_).code.length > 0 && wrapped_.code.length > 0, "CONFIG");
require(address(orders_) != address(receipts_), "CONFIG");
bootstrap = msg.sender;
control = control_;
orders = orders_;
receipts = receipts_;
wrapped = wrapped_;
}
// The state at deployment, set once by the deployer without waiting: the first tokens and versions. The vault
// must already be the only minter of its NFTs and receipts. Everything later comes from the control contract.
function initialize(address[] calldata tokens, address[] calldata versions_) external {
require(msg.sender == bootstrap && !initialized, "INITIALIZATION");
require(orders.minter() == address(this) && receipts.minter() == address(this), "MINTER");
require(tokens.length > 0, "TOKENS");
for (uint256 i; i < tokens.length; ++i) _listToken(tokens[i]);
for (uint256 i; i < versions_.length; ++i) _approve(versions_[i]);
initialized = true;
bootstrap = address(0);
}
modifier locked() {
require(status == FREE, "BUSY");
status = BUSY;
_;
status = FREE;
}
modifier onlySelf() {
require(msg.sender == address(this), "SELF");
_;
}
modifier onlyControl() {
require(msg.sender == control, "CONTROL");
_;
}
// ---------------------------------------------------------------- calls by anyone, with their own coins
// A new order on an open version. `coin` and `most`: which coin, and how much at most, may leave the caller's
// wallet in this call; coin 0 is the network's own coin, sent with the call and wrapped.
function place(address version, address coin, uint256 most, bytes calldata terms) external payable returns (bytes memory result) {
_begin(version, coin, most, false);
require(_canOpenOrders(version) && !_paused(version), "VERSION");
result = IOLinxRules(version).onPlace(msg.sender, msg.value, terms);
_finishCall();
}
// A take on an open or closed version, until its closing date.
function take(address version, address coin, uint256 most, bytes calldata terms) external payable returns (bytes memory result) {
_begin(version, coin, most, false);
require(_canTake(version) && !_paused(version), "VERSION");
result = IOLinxRules(version).onTake(msg.sender, msg.value, terms);
_finishCall();
}
// Only the order's holder, whatever its version's state: what is left and the unused deposit go to the holder.
function cancel(bytes32 id) external locked {
VaultEntry storage e = entries[id];
require(e.open && e.kind == ORDER && orders.ownerOf(uint256(id)) == msg.sender, "NOT_CANCELLABLE");
_endEntry(id, e, CANCELLED, false);
}
// Only the holder: the order ends here and its tokens and deposit fund a new order on another open version, which
// sees an ordinary place; what the new order does not use goes back to the holder. Nothing leaves the vault.
function move(bytes32 id, address version, bytes calldata terms) external payable returns (bytes memory result) {
VaultEntry storage e = entries[id];
require(e.open && e.kind == ORDER && orders.ownerOf(uint256(id)) == msg.sender, "NOT_MOVABLE");
require(version != e.version, "SAME_VERSION");
_begin(version, e.token, e.amount, true);
require(_canOpenOrders(version) && !_paused(version), "VERSION");
uint256 deposit = e.deposit;
held[e.version][e.token] -= e.amount;
e.open = false;
e.amount = 0;
e.deposit = 0;
orders.burn(uint256(id));
emit Closed(id, msg.sender, callLeft, deposit, MOVED);
callNative += deposit;
result = IOLinxRules(version).onPlace(msg.sender, callNative, terms);
_finishCall();
}
// Only a lock's taker, once its release time has passed: what is left goes back to the taker.
function release(bytes32 id) external locked {
VaultEntry storage e = entries[id];
require(e.open && e.kind == LOCK && e.holder == msg.sender && e.releaseAt != 0 && block.timestamp >= e.releaseAt, "NOT_RELEASABLE");
_endEntry(id, e, RELEASED, false);
}
// Only the holder, whatever its version's state: the order ends here and its tokens and deposit go to a later
// vault the control contract allows, which takes it in as it decides (`terms`); nothing passes through the wallet.
function moveToVault(bytes32 id, address to, bytes calldata terms) external payable locked returns (bytes memory result) {
VaultEntry storage e = entries[id];
require(e.open && e.kind == ORDER && orders.ownerOf(uint256(id)) == msg.sender, "NOT_MOVABLE");
require(destination[to], "DESTINATION");
uint256 amount = e.amount;
uint256 deposit = e.deposit;
IERC20 token = IERC20(e.token);
held[e.version][e.token] -= amount;
e.open = false;
e.amount = 0;
e.deposit = 0;
orders.burn(uint256(id));
emit Closed(id, msg.sender, amount, deposit, MOVED_OUT);
uint256 before = token.balanceOf(address(this));
if (amount > 0) token.safeApprove(to, amount);
result = IOLinxVaultImport(to).importOrder{value: deposit + msg.value}(msg.sender, e.token, amount, terms);
require(token.balanceOf(address(this)) + amount == before && token.allowance(address(this), to) == 0, "EXACT_TRANSFER");
}
// A held payout goes to its owner, and only to its owner; anyone may send it on (our services do), once it can
// arrive.
function claim(address owner) external locked {
uint256 amount = owed[owner];
require(amount > 0, "NOTHING_OWED");
owed[owner] = 0;
(bool sent, ) = owner.call{value: amount}("");
require(sent, "CLAIM_FAILED");
emit Claimed(owner, address(0), amount);
}
function claimTokens(address token, address owner) external locked {
uint256 amount = tokensOwed[token][owner];
require(amount > 0, "NOTHING_OWED");
tokensOwed[token][owner] = 0;
_push(token, owner, amount);
emit Claimed(owner, token, amount);
}
// ---------------------------------------------------------------- one call of a version
function _begin(address version, address coin, uint256 most, bool moving) private {
require(initialized, "NOT_INITIALIZED");
require(status == FREE, "BUSY");
status = BUSY;
callVersion = version;
callCaller = msg.sender;
callWrap = coin == address(0);
callCoin = callWrap ? wrapped : coin;
callMove = moving;
callLeft = most;
callNative = msg.value;
}
// What the call did not use goes back: of a moved order, its tokens; of the network's coin sent, the rest.
function _finishCall() private {
address caller = callCaller;
address coin = callCoin;
uint256 tokens = callMove ? callLeft : 0;
uint256 native = callNative;
callVersion = address(0);
callCaller = address(0);
callCoin = address(0);
callWrap = false;
callMove = false;
callLeft = 0;
callNative = 0;
if (tokens > 0) _push(coin, caller, tokens);
if (native > 0) _sendNative(caller, native);
if (tokens > 0 || native > 0) emit Returned(caller, coin, tokens, native);
status = FREE;
}
function _inCall() private view {
require(status == BUSY && callVersion == msg.sender && msg.sender != address(0), "NOT_IN_CALL");
}
function open(bytes32 id, uint8 kind, address coin, uint256 amount, uint256 deposit, address receiver, uint64 releaseAt) external {
_inCall();
require(coin == callCoin && tokenStatus[coin] == LISTED, "TOKEN");
require(id != bytes32(0) && entries[id].version == address(0), "ENTRY");
require(amount > 0, "AMOUNT");
if (kind == ORDER) require(_canOpenOrders(msg.sender) && releaseAt == 0, "ORDER");
else require(kind == LOCK, "KIND");
_spend(amount);
if (!callMove) {
if (callWrap) _wrap(amount);
else _pull(coin, callCaller, address(this), amount);
}
_useNative(deposit);
_hold(msg.sender, coin, amount);
entries[id] = VaultEntry(msg.sender, kind, true, coin, callCaller, releaseAt, amount, deposit);
if (kind == ORDER) orders.mint(callCaller, uint256(id), receiver);
else receipts.mint(callCaller, uint256(id));
emit Opened(id, msg.sender, callCaller, kind, coin, amount, deposit, releaseAt);
}
function collect(address coin, address to, uint256 amount) external {
_inCall();
require(!callMove, "MOVE");
require(amount > 0 && to != address(0) && to != address(this), "COLLECT");
require(coin == callCoin && tokenStatus[coin] == LISTED, "TOKEN");
_spend(amount);
if (callWrap) {
_wrap(amount);
_push(callCoin, to, amount);
} else _pull(callCoin, callCaller, to, amount);
emit Collected(msg.sender, callCaller, to, callCoin, amount);
}
function forward(address to, uint256 amount) external {
_inCall();
require(amount > 0 && to != address(0) && to != address(this), "FORWARD");
_useNative(amount);
emit Forwarded(msg.sender, to, amount, !_sendNative(to, amount));
}
function _spend(uint256 amount) private {
require(amount <= callLeft, "MOST");
callLeft -= amount;
}
function _useNative(uint256 amount) private {
require(amount <= callNative, "VALUE");
callNative -= amount;
}
function _wrap(uint256 amount) private {
_useNative(amount);
uint256 before = IERC20(wrapped).balanceOf(address(this));
IWrappedNative(wrapped).deposit{value: amount}();
require(IERC20(wrapped).balanceOf(address(this)) == before + amount, "EXACT_TRANSFER");
}
function _hold(address version, address token, uint256 amount) private {
uint256 total = held[version][token] + amount;
uint256 cap = ceiling[version][token];
require(cap == 0 || total <= cap, "CEILING");
held[version][token] = total;
}
// ---------------------------------------------------------------- a version's own entries
// A version may call these outside any call (a delivery) or inside its own call, never inside another's.
function _enterAsVersion() private returns (bool outer) {
if (status == FREE) {
status = BUSY;
return true;
}
_inCall();
}
function _leaveAsVersion(bool outer) private {
if (outer) status = FREE;
}
function _own(bytes32 id) private view returns (VaultEntry storage e) {
e = entries[id];
require(e.version == msg.sender && e.open, "ENTRY");
}
function pay(bytes32 id, address to, uint256 amount) external returns (bool sent) {
bool outer = _enterAsVersion();
VaultEntry storage e = _own(id);
require(amount > 0 && amount <= e.amount, "AMOUNT");
require(to != address(0), "TO");
if (e.kind == ORDER) require(!_retired(msg.sender), "RETIRED");
uint256 limit = dailyLimit[msg.sender][e.token];
if (limit != 0) {
uint256 day = block.timestamp / 1 days;
uint256 paid = paidOnDay[msg.sender][e.token][day] + amount;
require(paid <= limit, "DAILY_LIMIT");
paidOnDay[msg.sender][e.token][day] = paid;
}
e.amount -= amount;
held[msg.sender][e.token] -= amount;
sent = _payOut(e.token, to, amount);
emit Paid(id, to, amount, !sent);
_leaveAsVersion(outer);
}
function payDeposit(bytes32 id, address to, uint256 amount) external returns (bool sent) {
bool outer = _enterAsVersion();
VaultEntry storage e = _own(id);
require(amount > 0 && amount <= e.deposit, "AMOUNT");
require(to != address(0), "TO");
if (e.kind == ORDER) require(!_retired(msg.sender), "RETIRED");
e.deposit -= amount;
sent = _sendNative(to, amount);
emit DepositPaid(id, to, amount, !sent);
_leaveAsVersion(outer);
}
function close(bytes32 id) external {
bool outer = _enterAsVersion();
_endEntry(id, _own(id), ENDED_BY_VERSION, true);
_leaveAsVersion(outer);
}
// A lock's unused payment becomes its taker's own order under the same version, only while the version takes
// new orders (VA16) and the token is listed (a stopped token takes no new order); allowed while paused.
function convert(bytes32 lockId, bytes32 orderId, uint256 amount, address receiver) external {
bool outer = _enterAsVersion();
VaultEntry storage l = _own(lockId);
require(l.kind == LOCK && amount > 0 && amount <= l.amount, "AMOUNT");
require(_canOpenOrders(msg.sender), "ORDER");
require(tokenStatus[l.token] == LISTED, "TOKEN");
require(orderId != bytes32(0) && entries[orderId].version == address(0), "ENTRY");
l.amount -= amount;
entries[orderId] = VaultEntry(msg.sender, ORDER, true, l.token, l.holder, 0, amount, 0);
orders.mint(l.holder, uint256(orderId), receiver);
emit Converted(lockId, orderId, amount);
emit Opened(orderId, msg.sender, l.holder, ORDER, l.token, amount, 0, 0);
_leaveAsVersion(outer);
}
// Ends an entry: what is left and its deposit go to its holder (an order's NFT owner, a lock's taker), and its
// NFT or receipt is burned. Asked by its version, a payout the holder cannot take is held for it; asked by the
// holder, it must arrive.
function _endEntry(bytes32 id, VaultEntry storage e, uint8 how, bool holdIfRefused) private {
address holder = e.kind == ORDER ? orders.ownerOf(uint256(id)) : e.holder;
uint256 amount = e.amount;
uint256 deposit = e.deposit;
held[e.version][e.token] -= amount;
e.open = false;
e.amount = 0;
e.deposit = 0;
if (e.kind == ORDER) orders.burn(uint256(id));
else receipts.burn(uint256(id));
if (amount > 0) {
if (holdIfRefused) _payOut(e.token, holder, amount);
else _push(e.token, holder, amount);
}
if (deposit > 0) _sendNative(holder, deposit);
emit Closed(id, holder, amount, deposit, how);
}
// ---------------------------------------------------------------- set by the control contract alone
function approveVersion(address version) external onlyControl locked {
_approve(version);
}
// A closing date (zero: none) while the version is not retired. When it may move later, and that earlier is at
// once, is the control contract's rule.
function setClosingDate(address version, uint64 date) external onlyControl locked {
Version storage v = _known(version);
require(!_retired(version) && (date == 0 || date >= block.timestamp), "DATE");
v.closingDate = date;
emit ClosingDateSet(version, date);
}
// Paused until then (zero: not paused). A pause stops new orders and takes only.
function setPause(address version, uint64 until) external onlyControl locked {
_known(version).pausedUntil = until;
emit Paused(version, until);
}
function listToken(address token) external onlyControl locked {
_listToken(token);
}
// A stopped token takes no new entry; what is held in it can always leave.
function stopToken(address token) external onlyControl locked {
require(tokenStatus[token] == LISTED, "TOKEN");
tokenStatus[token] = STOPPED;
emit TokenStatusSet(token, STOPPED);
}
function setLimits(address version, address token, uint256 ceiling_, uint256 dailyLimit_) external onlyControl locked {
_known(version);
ceiling[version][token] = ceiling_;
dailyLimit[version][token] = dailyLimit_;
emit LimitsSet(version, token, ceiling_, dailyLimit_);
}
// The address of the order NFTs' or receipts' descriptions; nothing else about them can change.
function setBaseURI(address nft, string calldata baseURI_) external onlyControl locked {
require(nft == address(orders) || nft == address(receipts), "NFT");
IOLinxVaultOrders(nft).setBaseURI(baseURI_);
}
function setDestination(address vault, bool allowed) external onlyControl locked {
require(!allowed || (vault.code.length > 0 && vault != address(this)), "DESTINATION");
destination[vault] = allowed;
emit DestinationSet(vault, allowed);
}
function _approve(address version) private {
require(version.code.length > 0 && versions[version].state == 0, "VERSION");
require(IOLinxRules(version).vault() == address(this), "VAULT");
bytes32 family = IOLinxRules(version).family();
require(family != bytes32(0), "FAMILY");
address previous = openVersion[family];
if (previous != address(0)) versions[previous].state = CLOSED;
versions[version] = Version(family, APPROVED_OPEN, 0, 0);
openVersion[family] = version;
emit VersionApproved(version, family, previous);
}
function _listToken(address token) private {
require(token.code.length > 0 && tokenStatus[token] != LISTED, "TOKEN");
tokenStatus[token] = LISTED;
emit TokenStatusSet(token, LISTED);
}
function _known(address version) private view returns (Version storage v) {
v = versions[version];
require(v.state != 0, "VERSION");
}
// ---------------------------------------------------------------- views
function versionOf(address version) external view returns (bytes32 family, uint8 state, uint64 closingDate, uint64 pausedUntil, bool isRetired, bool isPaused) {
Version storage v = versions[version];
return (v.family, v.state, v.closingDate, v.pausedUntil, _retired(version), _paused(version));
}
function entryOf(bytes32 id) external view returns (VaultEntry memory) { return entries[id]; }
function amountOf(bytes32 id) external view returns (uint256) { return entries[id].amount; }
function depositOf(bytes32 id) external view returns (uint256) { return entries[id].deposit; }
function isOpen(bytes32 id) external view returns (bool) { return entries[id].open; }
function exists(bytes32 id) external view returns (bool) { return entries[id].version != address(0); }
function isListed(address token) external view returns (bool) { return tokenStatus[token] == LISTED; }
function canOpenOrders(address version) external view returns (bool) { return _canOpenOrders(version); }
function canTake(address version) external view returns (bool) { return _canTake(version); }
function retired(address version) external view returns (bool) { return _retired(version); }
function paused(address version) external view returns (bool) { return _paused(version); }
function _retired(address version) private view returns (bool) {
uint64 date = versions[version].closingDate;
return date != 0 && block.timestamp >= date;
}
function _paused(address version) private view returns (bool) {
return block.timestamp < versions[version].pausedUntil;
}
function _canOpenOrders(address version) private view returns (bool) {
return versions[version].state == APPROVED_OPEN && !_retired(version);
}
function _canTake(address version) private view returns (bool) {
return versions[version].state != 0 && !_retired(version);
}
// ---------------------------------------------------------------- exact token movement
// From the caller's wallet, to the vault or straight to an address, checked on both sides.
function _pull(address token, address from, address to, uint256 amount) private {
IERC20 erc20 = IERC20(token);
uint256 beforeFrom = erc20.balanceOf(from);
uint256 beforeTo = erc20.balanceOf(to);
erc20.safeTransferFrom(from, to, amount);
require(erc20.balanceOf(to) == beforeTo + amount && erc20.balanceOf(from) + amount == beforeFrom, "EXACT_TRANSFER");
}
function _push(address token, address to, uint256 amount) private {
IERC20 erc20 = IERC20(token);
uint256 beforeSelf = erc20.balanceOf(address(this));
uint256 beforeTo = erc20.balanceOf(to);
erc20.safeTransfer(to, amount);
require(erc20.balanceOf(to) == beforeTo + amount && erc20.balanceOf(address(this)) + amount == beforeSelf, "EXACT_TRANSFER");
}
// _push as a call that can fail by itself; only the vault makes it.
function pushOut(address token, address to, uint256 amount) external onlySelf {
_push(token, to, amount);
}
function _payOut(address token, address to, uint256 amount) private returns (bool sent) {
try this.pushOut(token, to, amount) {
return true;
} catch {
tokensOwed[token][to] += amount;
emit Held(to, token, amount);
return false;
}
}
function _sendNative(address to, uint256 amount) private returns (bool sent) {
(sent, ) = to.call{value: amount, gas: PUSH_GAS}("");
if (!sent) {
owed[to] += amount;
emit Held(to, address(0), amount);
}
}
}
npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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);
}
npm/@openzeppelin/[email protected]/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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.
*/
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].
*/
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);
}
npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
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");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
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");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
npm/@openzeppelin/[email protected]/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
* ====
*
* [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// 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);
}
}
}
}
project/contracts/vault/v1/IOLinxVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
// The kinds of entry the vault keeps. An order is tokens a maker offers; its holder is its order NFT's owner. A lock
// is the payment a taker locked for a trade between networks; its holder is the taker, who holds its receipt.
uint8 constant ORDER = 1;
uint8 constant LOCK = 2;
// One entry, as the vault reads it out.
struct VaultEntry {
address version;
uint8 kind;
bool open;
address token;
// The address the entry was opened for: an order's maker (its NFT may have changed hands since), a lock's taker.
address holder;
// A lock's release time (VA30): from then on its taker may take back what is left. Zero: never.
uint64 releaseAt;
uint256 amount;
uint256 deposit;
}
// A rules version, as the vault calls it. It is approved by the vault's admin and names the vault it works with and
// its family (its kind of trading: one open version per family takes new orders).
interface IOLinxRules {
function vault() external view returns (address);
function family() external view returns (bytes32);
// A call of the version for `caller` (the wallet that called the vault), with `value` the network's coin it may
// use (what the call sent, and in a move the moved order's deposit). While it runs, only this version may call
// the vault back (open, collect, forward, and its own entries). What it returns goes back to the caller.
function onPlace(address caller, uint256 value, bytes calldata terms) external returns (bytes memory);
function onTake(address caller, uint256 value, bytes calldata terms) external returns (bytes memory);
}
// What a rules version may ask of the vault, and what anyone may read.
interface IOLinxVault {
// During a call of the version, for the caller: opens an order (its NFT to the caller, with `receiver`) or a lock
// (its receipt to the caller), funded with `amount` of the call's coin and `deposit` of the network's coin.
function open(bytes32 id, uint8 kind, address coin, uint256 amount, uint256 deposit, address receiver, uint64 releaseAt) external;
// During a call of the version: the caller's coin straight to `to` (a swap's payment), counted in the call's most.
// `coin` is the coin the version expects; the call must be in it.
function collect(address coin, address to, uint256 amount) external;
// During a call of the version: network coin sent with the call to `to` (a delivery fee); held if refused.
function forward(address to, uint256 amount) external;
// The version's own entries, at any time. A payout that its receiver cannot take (whatever the address) is held
// for it; `sent` says whether it arrived.
function pay(bytes32 id, address to, uint256 amount) external returns (bool sent);
function payDeposit(bytes32 id, address to, uint256 amount) external returns (bool sent);
function close(bytes32 id) external;
function convert(bytes32 lockId, bytes32 orderId, uint256 amount, address receiver) external;
function entryOf(bytes32 id) external view returns (VaultEntry memory);
function amountOf(bytes32 id) external view returns (uint256);
function depositOf(bytes32 id) external view returns (uint256);
function isOpen(bytes32 id) external view returns (bool);
function exists(bytes32 id) external view returns (bool);
function isListed(address token) external view returns (bool);
function canOpenOrders(address version) external view returns (bool);
function canTake(address version) external view returns (bool);
function retired(address version) external view returns (bool);
function orders() external view returns (IOLinxVaultOrders);
function receipts() external view returns (IOLinxVaultReceipts);
// The control contract: the only one that approves versions, sets their dates and pauses, lists tokens, sets
// limits and the NFTs' descriptions, and names the vaults orders may move to. Versions take their settings from it.
function control() external view returns (address);
}
// What the control contract (OLinxControl) asks of the vault, and reads from it.
interface IOLinxVaultGoverned {
function control() external view returns (address);
function versionOf(address version) external view returns (bytes32 family, uint8 state, uint64 closingDate, uint64 pausedUntil, bool isRetired, bool isPaused);
function approveVersion(address version) external;
function setClosingDate(address version, uint64 date) external;
function setPause(address version, uint64 until) external;
function listToken(address token) external;
function stopToken(address token) external;
function setLimits(address version, address token, uint256 ceiling, uint256 dailyLimit) external;
function setBaseURI(address nft, string calldata baseURI_) external;
function setDestination(address vault, bool allowed) external;
}
// A later vault that takes in orders moved from this one (VA31). The vault moving an order allows the later vault to
// take exactly `amount` of `token` from it, calls this with the order's deposit (and any coin the holder sent) as
// value, and checks afterwards that exactly `amount` left. What the later vault does with the order is its own.
interface IOLinxVaultImport {
function importOrder(address holder, address token, uint256 amount, bytes calldata terms) external payable returns (bytes memory);
}
// The vault's order NFTs and trade receipts (v2): the vault is their only minter.
interface IOLinxVaultOrders {
function mint(address to, uint256 id, address receiver) external;
function burn(uint256 id) external;
function ownerOf(uint256 id) external view returns (address);
function receiverOf(uint256 id) external view returns (address);
function minter() external view returns (address);
function setBaseURI(string calldata baseURI_) external;
}
interface IOLinxVaultReceipts {
function mint(address to, uint256 id) external;
function burn(uint256 id) external;
function minter() external view returns (address);
function setBaseURI(string calldata baseURI_) external;
}
// The network's own coin in its token form (WETH, WBNB, WPOL).
interface IWrappedNative {
function deposit() external payable;
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.