// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10 <0.9.0;
import {TablelandPolicy} from "../TablelandPolicy.sol";
/**
* @dev Interface of a TablelandTables compliant contract.
*/
interface ITablelandTables {
/**
* The caller is not authorized.
*/
error Unauthorized();
/**
* RunSQL was called with a query length greater than maximum allowed.
*/
error MaxQuerySizeExceeded(uint256 querySize, uint256 maxQuerySize);
/**
* @dev Emitted when `owner` creates a new table.
*
* owner - the to-be owner of the table
* tableId - the table id of the new table
* statement - the SQL statement used to create the table
*/
event CreateTable(address owner, uint256 tableId, string statement);
/**
* @dev Emitted when a table is transferred from `from` to `to`.
*
* Not emmitted when a table is created.
* Also emitted after a table has been burned.
*
* from - the address that transfered the table
* to - the address that received the table
* tableId - the table id that was transferred
*/
event TransferTable(address from, address to, uint256 tableId);
/**
* @dev Emitted when `caller` runs a SQL statement.
*
* caller - the address that is running the SQL statement
* isOwner - whether or not the caller is the table owner
* tableId - the id of the target table
* statement - the SQL statement to run
* policy - an object describing how `caller` can interact with the table (see {TablelandPolicy})
*/
event RunSQL(
address caller,
bool isOwner,
uint256 tableId,
string statement,
TablelandPolicy policy
);
/**
* @dev Emitted when a table's controller is set.
*
* tableId - the id of the target table
* controller - the address of the controller (EOA or contract)
*/
event SetController(uint256 tableId, address controller);
/**
* @dev Struct containing parameters needed to run a mutating sql statement
*
* tableId - the id of the target table
* statement - the SQL statement to run
* - the statement type can be any of INSERT, UPDATE, DELETE, GRANT, REVOKE
*
*/
struct Statement {
uint256 tableId;
string statement;
}
/**
* @dev Creates a new table owned by `owner` using `statement` and returns its `tableId`.
*
* owner - the to-be owner of the new table
* statement - the SQL statement used to create the table
* - the statement type must be CREATE
*
* Requirements:
*
* - contract must be unpaused
*/
function create(
address owner,
string memory statement
) external payable returns (uint256);
/**
* @dev Creates multiple new tables owned by `owner` using `statements` and returns array of `tableId`s.
*
* owner - the to-be owner of the new table
* statements - the SQL statements used to create the tables
* - each statement type must be CREATE
*
* Requirements:
*
* - contract must be unpaused
*/
function create(
address owner,
string[] calldata statements
) external payable returns (uint256[] memory);
/**
* @dev Runs a mutating SQL statement for `caller` using `statement`.
*
* caller - the address that is running the SQL statement
* tableId - the id of the target table
* statement - the SQL statement to run
* - the statement type can be any of INSERT, UPDATE, DELETE, GRANT, REVOKE
*
* Requirements:
*
* - contract must be unpaused
* - `msg.sender` must be `caller`
* - `tableId` must exist and be the table being mutated
* - `caller` must be authorized by the table controller
* - `statement` must be less than or equal to 35000 bytes
*/
function mutate(
address caller,
uint256 tableId,
string calldata statement
) external payable;
/**
* @dev Runs an array of mutating SQL statements for `caller`
*
* caller - the address that is running the SQL statement
* statements - an array of structs containing the id of the target table and coresponding statement
* - the statement type can be any of INSERT, UPDATE, DELETE, GRANT, REVOKE
*
* Requirements:
*
* - contract must be unpaused
* - `msg.sender` must be `caller`
* - `tableId` must be the table being muated in each struct's statement
* - `caller` must be authorized by the table controller if the statement is mutating
* - each struct inside `statements` must have a `tableId` that corresponds to table being mutated
* - each struct inside `statements` must have a `statement` that is less than or equal to 35000 bytes after normalization
*/
function mutate(
address caller,
ITablelandTables.Statement[] calldata statements
) external payable;
/**
* @dev Sets the controller for a table. Controller can be an EOA or contract address.
*
* When a table is created, it's controller is set to the zero address, which means that the
* contract will not enforce write access control. In this situation, validators will not accept
* transactions from non-owners unless explicitly granted access with "GRANT" SQL statements.
*
* When a controller address is set for a table, validators assume write access control is
* handled at the contract level, and will accept all transactions.
*
* You can unset a controller address for a table by setting it back to the zero address.
* This will cause validators to revert back to honoring owner and GRANT/REVOKE based write access control.
*
* caller - the address that is setting the controller
* tableId - the id of the target table
* controller - the address of the controller (EOA or contract)
*
* Requirements:
*
* - contract must be unpaused
* - `msg.sender` must be `caller` and owner of `tableId`
* - `tableId` must exist
* - `tableId` controller must not be locked
*/
function setController(
address caller,
uint256 tableId,
address controller
) external;
/**
* @dev Returns the controller for a table.
*
* tableId - the id of the target table
*/
function getController(uint256 tableId) external returns (address);
/**
* @dev Locks the controller for a table _forever_. Controller can be an EOA or contract address.
*
* Although not very useful, it is possible to lock a table controller that is set to the zero address.
*
* caller - the address that is locking the controller
* tableId - the id of the target table
*
* Requirements:
*
* - contract must be unpaused
* - `msg.sender` must be `caller` and owner of `tableId`
* - `tableId` must exist
* - `tableId` controller must not be locked
*/
function lockController(address caller, uint256 tableId) external;
/**
* @dev Sets the contract base URI.
*
* baseURI - the new base URI
*
* Requirements:
*
* - `msg.sender` must be contract owner
*/
function setBaseURI(string memory baseURI) external;
/**
* @dev Pauses the contract.
*
* Requirements:
*
* - `msg.sender` must be contract owner
* - contract must be unpaused
*/
function pause() external;
/**
* @dev Unpauses the contract.
*
* Requirements:
*
* - `msg.sender` must be contract owner
* - contract must be paused
*/
function unpause() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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 largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10 <0.9.0;
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
/**
* @dev Library of helpers for generating SQL statements from common parameters.
*/
library SQLHelpers {
/**
* @dev Generates a properly formatted table name from a prefix and table id.
*
* prefix - the user generated table prefix as a string
* tableId - the Tableland generated tableId as a uint256
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toNameFromId(
string memory prefix,
uint256 tableId
) internal view returns (string memory) {
return
string(
abi.encodePacked(
prefix,
"_",
Strings.toString(block.chainid),
"_",
Strings.toString(tableId)
)
);
}
/**
* @dev Generates a CREATE statement based on a desired schema and table prefix.
*
* schema - a comma seperated string indicating the desired prefix. Example: "int id, text name"
* prefix - the user generated table prefix as a string
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toCreateFromSchema(
string memory schema,
string memory prefix
) internal view returns (string memory) {
return
string(
abi.encodePacked(
"CREATE TABLE ",
prefix,
"_",
Strings.toString(block.chainid),
"(",
schema,
")"
)
);
}
/**
* @dev Generates an INSERT statement based on table prefix, tableId, columns, and values.
*
* prefix - the user generated table prefix as a string.
* tableId - the Tableland generated tableId as a uint256.
* columns - a string encoded ordered list of columns that will be updated. Example: "name, age".
* values - a string encoded ordered list of values that will be inserted wrapped in parentheses. Example: "'jerry', 24". Values order must match column order.
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toInsert(
string memory prefix,
uint256 tableId,
string memory columns,
string memory values
) internal view returns (string memory) {
string memory name = toNameFromId(prefix, tableId);
return
string(
abi.encodePacked(
"INSERT INTO ",
name,
"(",
columns,
")VALUES(",
values,
")"
)
);
}
/**
* @dev Generates an INSERT statement based on table prefix, tableId, columns, and values.
*
* prefix - the user generated table prefix as a string.
* tableId - the Tableland generated tableId as a uint256.
* columns - a string encoded ordered list of columns that will be updated. Example: "name, age".
* values - an array where each item is a string encoded ordered list of values.
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toBatchInsert(
string memory prefix,
uint256 tableId,
string memory columns,
string[] memory values
) internal view returns (string memory) {
string memory name = toNameFromId(prefix, tableId);
string memory insert = string(
abi.encodePacked("INSERT INTO ", name, "(", columns, ")VALUES")
);
for (uint256 i = 0; i < values.length; i++) {
if (i == 0) {
insert = string(abi.encodePacked(insert, "(", values[i], ")"));
} else {
insert = string(abi.encodePacked(insert, ",(", values[i], ")"));
}
}
return insert;
}
/**
* @dev Generates an Update statement based on table prefix, tableId, setters, and filters.
*
* prefix - the user generated table prefix as a string
* tableId - the Tableland generated tableId as a uint256
* setters - a string encoded set of updates. Example: "name='tom', age=26"
* filters - a string encoded list of filters or "" for no filters. Example: "id<2 and name!='jerry'"
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toUpdate(
string memory prefix,
uint256 tableId,
string memory setters,
string memory filters
) internal view returns (string memory) {
string memory name = toNameFromId(prefix, tableId);
string memory filter = "";
if (bytes(filters).length > 0) {
filter = string(abi.encodePacked(" WHERE ", filters));
}
return
string(abi.encodePacked("UPDATE ", name, " SET ", setters, filter));
}
/**
* @dev Generates a Delete statement based on table prefix, tableId, and filters.
*
* prefix - the user generated table prefix as a string.
* tableId - the Tableland generated tableId as a uint256.
* filters - a string encoded list of filters. Example: "id<2 and name!='jerry'".
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function toDelete(
string memory prefix,
uint256 tableId,
string memory filters
) internal view returns (string memory) {
string memory name = toNameFromId(prefix, tableId);
return
string(abi.encodePacked("DELETE FROM ", name, " WHERE ", filters));
}
/**
* @dev Add single quotes around a string value
*
* input - any input value.
*
*/
function quote(string memory input) internal pure returns (string memory) {
return string(abi.encodePacked("'", input, "'"));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10 <0.9.0;
import {ITablelandTables} from "../interfaces/ITablelandTables.sol";
/**
* @dev Helper library for getting an instance of ITablelandTables for the currently executing EVM chain.
*/
library TablelandDeployments {
/**
* Current chain does not have a TablelandTables deployment.
*/
error ChainNotSupported(uint256 chainid);
// TablelandTables address on Ethereum.
address internal constant MAINNET =
0x012969f7e3439a9B04025b5a049EB9BAD82A8C12;
// TablelandTables address on Ethereum.
address internal constant HOMESTEAD = MAINNET;
// TablelandTables address on Optimism.
address internal constant OPTIMISM =
0xfad44BF5B843dE943a09D4f3E84949A11d3aa3e6;
// TablelandTables address on Arbitrum One.
address internal constant ARBITRUM =
0x9aBd75E8640871A5a20d3B4eE6330a04c962aFfd;
// TablelandTables address on Arbitrum Nova.
address internal constant ARBITRUM_NOVA =
0x1A22854c5b1642760a827f20137a67930AE108d2;
// TablelandTables address on Polygon.
address internal constant MATIC =
0x5c4e6A9e5C1e1BF445A062006faF19EA6c49aFeA;
// TablelandTables address on Filecoin.
address internal constant FILECOIN =
0x59EF8Bf2d6c102B4c42AEf9189e1a9F0ABfD652d;
// TablelandTables address on Ethereum Sepolia.
address internal constant SEPOLIA =
0xc50C62498448ACc8dBdE43DA77f8D5D2E2c7597D;
// TablelandTables address on Optimism Goerli.
address internal constant OPTIMISM_GOERLI =
0xC72E8a7Be04f2469f8C2dB3F1BdF69A7D516aBbA;
// TablelandTables address on Arbitrum Goerli.
address internal constant ARBITRUM_GOERLI =
0x033f69e8d119205089Ab15D340F5b797732f646b;
// TablelandTables address on Polygon Mumbai.
address internal constant MATICMUM =
0x4b48841d4b32C4650E4ABc117A03FE8B51f38F68;
// TablelandTables address on Filecoin Calibration.
address internal constant FILECOIN_CALIBRATION =
0x030BCf3D50cad04c2e57391B12740982A9308621;
// TablelandTables address on for use with https://github.com/tablelandnetwork/local-tableland.
address internal constant LOCAL_TABLELAND =
0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512;
/**
* @dev Returns an interface to Tableland for the currently executing EVM chain.
*
* The selection order is meant to reduce gas on more expensive chains.
*
* Requirements:
*
* - block.chainid must refer to a supported chain.
*/
function get() internal view returns (ITablelandTables) {
if (block.chainid == 1) {
return ITablelandTables(MAINNET);
} else if (block.chainid == 10) {
return ITablelandTables(OPTIMISM);
} else if (block.chainid == 42161) {
return ITablelandTables(ARBITRUM);
} else if (block.chainid == 42170) {
return ITablelandTables(ARBITRUM_NOVA);
} else if (block.chainid == 137) {
return ITablelandTables(MATIC);
} else if (block.chainid == 314) {
return ITablelandTables(FILECOIN);
} else if (block.chainid == 11155111) {
return ITablelandTables(SEPOLIA);
} else if (block.chainid == 420) {
return ITablelandTables(OPTIMISM_GOERLI);
} else if (block.chainid == 421613) {
return ITablelandTables(ARBITRUM_GOERLI);
} else if (block.chainid == 80001) {
return ITablelandTables(MATICMUM);
} else if (block.chainid == 314159) {
return ITablelandTables(FILECOIN_CALIBRATION);
} else if (block.chainid == 31337) {
return ITablelandTables(LOCAL_TABLELAND);
} else {
revert ChainNotSupported(block.chainid);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10 <0.9.0;
/**
* @dev Object defining how a table can be accessed.
*/
struct TablelandPolicy {
// Whether or not the table should allow SQL INSERT statements.
bool allowInsert;
// Whether or not the table should allow SQL UPDATE statements.
bool allowUpdate;
// Whether or not the table should allow SQL DELETE statements.
bool allowDelete;
// A conditional clause used with SQL UPDATE and DELETE statements.
// For example, a value of "foo > 0" will concatenate all SQL UPDATE
// and/or DELETE statements with "WHERE foo > 0".
// This can be useful for limiting how a table can be modified.
// Use {Policies-joinClauses} to include more than one condition.
string whereClause;
// A conditional clause used with SQL INSERT statements.
// For example, a value of "foo > 0" will concatenate all SQL INSERT
// statements with a check on the incoming data, i.e., "CHECK (foo > 0)".
// This can be useful for limiting how table data ban be added.
// Use {Policies-joinClauses} to include more than one condition.
string withCheck;
// A list of SQL column names that can be updated.
string[] updatableColumns;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "@tableland/evm/contracts/utils/TablelandDeployments.sol";
import "@tableland/evm/contracts/utils/SQLHelpers.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
contract Web3WizzController is Ownable, IERC721Receiver{
uint256 public tableId; //created beforehand
string private constant _TABLE_PREFIX = "web3wizz";
ITablelandTables tableland = TablelandDeployments.get();
// Add a constructor that creates and inserts data
// constructor(address _initialOwner, uint256 _tableId) Ownable(_initialOwner) {
constructor(address _initialOwner) Ownable(_initialOwner) {
// tableId = _tableId;
tableId = tableland.create(
address(this),
SQLHelpers.toCreateFromSchema(
"projectID text primary key,"
"owner text,"
"storageID text,"
"extraRef text", _TABLE_PREFIX
)
);
}
// Let anyone insert into the table
function insertIntoTable(
string memory _projectID,
string memory _storageID,
string memory _extraRef
) external {
tableland.mutate(
address(this),
tableId,
SQLHelpers.toInsert(
_TABLE_PREFIX,
tableId,
"owner, projectID, storageID, extraRef",
string.concat(
SQLHelpers.quote(Strings.toHexString(msg.sender)),
",",
SQLHelpers.quote(_projectID), // Insert the caller's address
",",
SQLHelpers.quote(_storageID),
",",
SQLHelpers.quote(_extraRef)
)
)
);
}
// Update only the row that the caller inserted
function updateTable(
string memory _owner,
string memory _projectID,
string memory _storageID,
string memory _extraRef
) external {
string memory setters =
string.concat(
"owner=", SQLHelpers.quote(_owner), ",",
"projectID=", SQLHelpers.quote(_projectID), ",",
"_storageID=", SQLHelpers.quote(_storageID), ",",
"_extraRef=", SQLHelpers.quote(_extraRef));
string memory filters = string.concat("owner=", SQLHelpers.quote(Strings.toHexString(msg.sender)));
tableland.mutate(
address(this),
tableId,
SQLHelpers.toUpdate(_TABLE_PREFIX, tableId, setters, filters)
);
}
// set tableID;
function setTableId(uint256 _tableId) external onlyOwner {
tableId = _tableId;
}
// Set the ACL controller to enable row-level writes with dynamic policies
function setAccessControl(address controller) external onlyOwner {
tableland.setController(
address(this), // Table owner, i.e., this contract
tableId,
controller // Set the controller address—a separate controller contract
);
}
// Needed for the contract to own a table
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
}
{
"compilationTarget": {
"contracts/Web3WizzController.sol": "Web3WizzController"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": false,
"runs": 200
},
"remappings": [],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_initialOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"chainid","type":"uint256"}],"name":"ChainNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"StringsInsufficientHexLength","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"internalType":"string","name":"_projectID","type":"string"},{"internalType":"string","name":"_storageID","type":"string"},{"internalType":"string","name":"_extraRef","type":"string"}],"name":"insertIntoTable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"controller","type":"address"}],"name":"setAccessControl","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tableId","type":"uint256"}],"name":"setTableId","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tableId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_owner","type":"string"},{"internalType":"string","name":"_projectID","type":"string"},{"internalType":"string","name":"_storageID","type":"string"},{"internalType":"string","name":"_extraRef","type":"string"}],"name":"updateTable","outputs":[],"stateMutability":"nonpayable","type":"function"}]