Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/examples/PoSQLHelloWorld.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ParamsBuilder, ProofOfSqlTable} from "../PoSQL.sol";
import {IQueryCallback} from "../IQueryCallback.sol";
import {IQueryRouter} from "../query-router/interfaces/IQueryRouter.sol";
/// @title PoSQLHelloWorld
/// @notice Example "Hello World"-style contract of a Proof of SQL query.
/// @dev This contract uses QueryRouter to pay for and execute the query.
/// the query is a simple SQL query that returns the number of ethereum contracts created by msg.sender.
/// note: make sure that this contract holds SXT enough to cover the query payment. Also this is a simple
/// example and does not include zero address checks and other security checks.
/// @dev to deploy this contract, use the DeployPoSQLHelloWorld script:
/// forge script script/deployPoSQLHelloWorld.s.sol:DeployPoSQLHelloWorld --broadcast --rpc-url=$ETH_RPC_URL --private-key=$PRIVATE_KEY --verify -vvvvv
contract PoSQLHelloWorld is IQueryCallback {
using SafeERC20 for IERC20;
/// @notice QueryRouter contract address
address public immutable QUERY_ROUTER;
/// @notice Proof of SQL version hash
bytes32 public immutable VERSION;
/// @notice SXT token address
address public immutable SXT;
/// @notice The ammount of SXT to pay for the query
uint256 public immutable PAYMENT_AMOUNT;
uint256 public constant MAX_GAS_PRICE = 1e6;
uint64 public constant GAS_LIMIT = 1e6;
/// @dev hex-serialized SQL query plan:
/// SELECT * FROM TUTORIAL_74334C989D37A3416B850E1DD622BF5410D18674.HELLO_WORLD WHERE LONGITUDE=60
bytes public constant QUERY_PLAN =
hex"0000000000000001000000000000003d5455544f5249414c5f373433333443393839443337413334313642383530453144443632324246353431304431383637342e48454c4c4f5f574f524c4400000000000000050000000000000000000000000000000249440000000b000000000000000000000000000000044e414d4500000007000000000000000000000000000000084c4154495455444500000005000000000000000000000000000000094c4f4e4749545544450000000500000000000000000000000000000004415245410000000500000000000000050000000000000002494400000000000000044e414d4500000000000000084c4154495455444500000000000000094c4f4e474954554445000000000000000441524541000000000000000000000000000000020000000000000000000000030000000100000005000000000000003c0000000000000005000000000000000000000000000000000000000000000001000000000000000000000002000000000000000000000003000000000000000000000004";
constructor(address queryRouter, bytes32 version, address sxt, uint248 amount) {
QUERY_ROUTER = queryRouter;
VERSION = version;
SXT = sxt;
PAYMENT_AMOUNT = amount;
}
/// @notice Pay for and execute a "Hello World"-style query.
function query() external {
// 0. pull SXT from the caller (must have approved this contract beforehand)
IERC20(SXT).safeTransferFrom(msg.sender, address(this), PAYMENT_AMOUNT);
// 1. approve payment to be spent by QueryRouter, that will cover PoSQLVerifier's fees and fulfillment callback gas.
// Note: make sure that the caller address holds at least `PAYMENT_AMOUNT` of SXT.
IERC20(SXT).forceApprove(QUERY_ROUTER, PAYMENT_AMOUNT); // use forceApprove to handle nonzero allowances
// 2. Assemble the SQL parameters using the `ParamsBuilder` library
bytes[] memory queryParameters = new bytes[](0);
bytes memory serializedParams = ParamsBuilder.serializeParamArray(queryParameters);
// 3. Assemble the request needed to run the query
IQueryRouter.Query memory queryToRequest = IQueryRouter.Query({
version: VERSION, innerQuery: QUERY_PLAN, parameters: serializedParams, metadata: hex""
});
// 4. Assemble the information needed to call the callback
IQueryRouter.Callback memory callback = IQueryRouter.Callback({
maxGasPrice: MAX_GAS_PRICE,
gasLimit: GAS_LIMIT,
callbackContract: address(this),
selector: IQueryCallback.queryCallback.selector,
callbackData: ""
});
// 5. Execute the query.
IQueryRouter(QUERY_ROUTER) // aderyn-ignore unchecked-return
.requestQuery(queryToRequest, callback, PAYMENT_AMOUNT, uint64(block.timestamp + 1 hours));
}
/// @notice Example event emitting the query result.
event QueryFulfilled(int64 longitude);
/// @inheritdoc IQueryCallback
/// @notice Handle the query result.
/// @dev This will be called once the query has been executed and verified on-chain.
function queryCallback(bytes32, bytes calldata queryResult, bytes calldata) external {
// Use the `ProofOfSqlTable` to deserialize and read data from the result
(, ProofOfSqlTable.Table memory tableResult) = ProofOfSqlTable.__deserializeFromBytes(queryResult);
int64 longitude = ProofOfSqlTable.readBigIntColumn(tableResult, 3)[0];
// Emit the count.
emit QueryFulfilled(longitude);
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"src/PoSQL.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// forge-lint: disable-start(unused-import)
/* solhint-disable no-unused-import */
import {ParamsBuilder} from "sxt-proof-of-sql/src/client/ParamsBuilder.post.sol"; // aderyn-ignore unused-import
import {ProofOfSqlTable} from "sxt-proof-of-sql/src/client/PoSQLTable.post.sol"; // aderyn-ignore unused-import
import {PoSQLVerifier} from "./PoSQLVerifier.sol"; // aderyn-ignore unused-import
/* solhint-enable no-unused-import */
/// forge-lint: disable-end(unused-import)
"
},
"src/IQueryCallback.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// This interface is NOT a required step in the process of writing a Proof of SQL query within your smart contract.
// The only aspect of this interface that is required for your contract is that there be some function with the same
// signature as `queryCallback`. This interface is here for anyone that wants to enforce that the function is on their contract.
interface IQueryCallback {
/**
* @notice Callback function for handling successful query results.
* @dev This function is invoked by the IQueryRouter contract upon successful fulfillment of a query.
* @param queryHash The unique identifier for the query.
* @param queryResult The result of the query.
* @param callbackData Additional data that was originally passed with the query.
*/
function queryCallback(bytes32 queryHash, bytes calldata queryResult, bytes calldata callbackData) external;
}
"
},
"src/query-router/interfaces/IQueryRouter.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @title IQueryRouter
/// @author Placeholder
/// @notice Interface for querying external data sources with cryptographic proofs
interface IQueryRouter {
/// @notice Query details
/// @param version Query version identifier
/// @param innerQuery Encoded, version-dependent query payload
/// @param parameters Encoded parameters for the query
/// @param metadata Encoded metadata for the query
struct Query {
bytes32 version;
bytes innerQuery;
bytes parameters;
bytes metadata;
}
/// @notice Callback execution details
/// @param maxGasPrice Max native gas price allowed for the callback
/// @param gasLimit Gas limit forwarded to the callback contract
/// @param callbackContract Address of the contract to call back
/// @param selector Function selector to call on the callback contract
/// @param callbackData Opaque callback-specific data passed to the callback
struct Callback {
uint256 maxGasPrice;
uint64 gasLimit;
address callbackContract;
bytes4 selector;
bytes callbackData;
}
/// @notice Emitted when a query is requested
/// @param queryId Unique identifier for the query
/// @param queryNonce Nonce used when the query was created
/// @param requester Address that requested the query
/// @param query Query details
/// @param callback Callback details
/// @param paymentAmount Amount of tokens held pending fulfillment
/// @param timeout Timestamp after which cancellation is allowed
event QueryRequested(
bytes32 indexed queryId,
uint64 indexed queryNonce,
address indexed requester,
Query query,
Callback callback,
uint256 paymentAmount,
uint64 timeout
);
/// @notice Emitted when a query has been fulfilled (logical fulfillment/result)
/// @param queryId Unique identifier for the query
/// @param fulfiller Address that fulfilled the query
/// @param result The query result data
event QueryFulfilled(bytes32 indexed queryId, address indexed fulfiller, bytes result);
/// @notice Emitted when a payout for a fulfilled query occurred (payments/refunds)
/// @param queryId Unique identifier for the query
/// @param fulfiller Address that fulfilled the query
/// @param refundRecipient Address that received a refund (if any)
/// @param fulfillerAmount Amount paid to the fulfiller for this fulfillment
/// @param refundAmount Amount refunded to the refundRecipient (if any)
event PayoutOccurred(
bytes32 indexed queryId,
address indexed fulfiller,
address indexed refundRecipient,
uint256 fulfillerAmount,
uint256 refundAmount
); // solhint-disable-line gas-indexed-events
/// @notice Emitted when a query is cancelled
/// @param queryId Unique identifier for the query
/// @param refundRecipient Address that received the refund
/// @param refundAmount Amount refunded
event QueryCancelled(bytes32 indexed queryId, address indexed refundRecipient, uint256 indexed refundAmount);
/// @notice Emitted when open fulfillment is toggled
/// @param enabled Whether open fulfillment is now enabled
event OpenFulfillmentToggled(bool indexed enabled);
/// @notice Emitted when the base cost used by the router is updated
/// @param newBaseCost The new base cost value
event BaseCostUpdated(uint256 indexed newBaseCost);
/// @notice Emitted when a version is set
/// @param version The string version
/// @param versionHash The keccak256 hash of the version
/// @param verifier The verifier contract address associated with the version
event VersionSet(string version, bytes32 indexed versionHash, address indexed verifier);
/// @notice Thrown when a query is not found or unauthorized cancellation is attempted
error QueryNotFound(); // aderyn-ignore unused-error
/// @notice Thrown when a query cancellation is attempted before the timeout
error QueryTimeoutNotReached(); // aderyn-ignore unused-error
/// @notice Thrown when the query version is not supported by the router
error UnsupportedQueryVersion(); // aderyn-ignore unused-error
/// @notice Register a verifier contract address to a version string
/// @param version The string version to hash
/// @param verifier The contract address to associate with the version
function registerVerifierToVersion(string calldata version, address verifier) external;
/// @notice Set the base cost for queries
/// @param newBaseCost The new base cost
function setBaseCost(uint256 newBaseCost) external;
/// @notice Cancel a pending query and refund the payment
/// @param queryId Unique identifier for the query to cancel
function cancelQuery(bytes32 queryId) external;
/// @notice Request a query to be executed.
/// @param query Query struct containing query string, parameters, and version.
/// @param callback Callback struct containing callback details.
/// @param paymentAmount Amount of tokens to hold pending fulfillment.
/// @param timeout Timestamp after which cancellation is allowed
/// @return queryId Unique ID for this query.
function requestQuery(Query calldata query, Callback calldata callback, uint256 paymentAmount, uint64 timeout)
external
returns (bytes32 queryId);
/// @notice Fulfill a query by providing its data and proof.
/// @param query Query struct for the original request.
/// @param callback Callback struct for the original request.
/// @param queryNonce Nonce used when the query was created.
/// @param proof Encoded proof containing the query result and cryptographic proof.
function fulfillQuery(Query calldata query, Callback calldata callback, uint64 queryNonce, bytes calldata proof)
external;
/// @notice Toggle open fulfillment on or off
/// @param enabled True to allow anyone to fulfill, false to restrict to FULFILLER_ROLE
function setOpenFulfillment(bool enabled) external;
/// @notice Verify a query result without executing its callback.
/// @param query Query struct for the original request.
/// @param proof Encoded proof containing the query result and cryptographic proof.
/// @return result The query result data extracted from the proof.
function verifyQuery(Query calldata query, bytes calldata proof) external view returns (bytes memory result);
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/interfaces/IERC1363.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
"
},
"dependencies/sxt-proof-of-sql-0.123.10/src/client/ParamsBuilder.post.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
// This is licensed under the Cryptographic Open Software License 1.0
pragma solidity ^0.8.28;
import "../base/Constants.sol";
import "../base/Errors.sol";
/// @title ParamsBuilder
/// @dev Library for constructing an array of sql params
library ParamsBuilder {
/// @dev Returns a serialized array of parameters
/// @param arrayOfSerializedParamElements An array of serialized parameters
/// @return serializedParams The serialized array of parameters
function serializeParamArray(bytes[] memory arrayOfSerializedParamElements)
internal
pure
returns (bytes memory serializedParams)
{
uint256 uncastLength = arrayOfSerializedParamElements.length;
if (uncastLength > MAX_UINT64) {
revert Errors.TooManyParameters();
} else {
uint64 length = uint64(uncastLength);
serializedParams = abi.encodePacked(length);
for (uint64 i = 0; i < length; ++i) {
serializedParams = abi.encodePacked(serializedParams, arrayOfSerializedParamElements[i]);
}
}
}
/// @dev Returns an array of parameters
/// @param serializedParams The serialized parameters
/// @return params The parameters as scalars
function deserializeParamArray(bytes calldata serializedParams) internal pure returns (uint256[] memory params) {
uint64 length;
assembly {
length := shr(UINT64_PADDING_BITS, calldataload(serializedParams.offset))
}
params = new uint256[](length);
assembly {
function exclude_coverage_start_read_data_type() {} // solhint-disable-line no-empty-blocks
function read_data_type(ptr) -> ptr_out, data_type {
data_type := shr(UINT32_PADDING_BITS, calldataload(ptr))
ptr_out := add(ptr, UINT32_SIZE)
switch data_type
case 0 { case_const(0, DATA_TYPE_BOOLEAN_VARIANT) }
case 2 { case_const(2, DATA_TYPE_TINYINT_VARIANT) }
case 3 { case_const(3, DATA_TYPE_SMALLINT_VARIANT) }
case 4 { case_const(4, DATA_TYPE_INT_VARIANT) }
case 5 { case_const(5, DATA_TYPE_BIGINT_VARIANT) }
case 7 { case_const(7, DATA_TYPE_VARCHAR_VARIANT) }
case 8 {
case_const(8, DATA_TYPE_DECIMAL75_VARIANT)
ptr_out := add(ptr_out, UINT8_SIZE) // Skip precision
ptr_out := add(ptr_out, INT8_SIZE) // Skip scale
}
case 9 {
case_const(9, DATA_TYPE_TIMESTAMP_VARIANT)
ptr_out := add(ptr_out, UINT32_SIZE) // Skip timeunit
ptr_out := add(ptr_out, INT32_SIZE) // Skip timezone
}
case 10 { case_const(10, DATA_TYPE_SCALAR_VARIANT) }
case 11 { case_const(11, DATA_TYPE_VARBINARY_VARIANT) }
default { err(ERR_UNSUPPORTED_DATA_TYPE_VARIANT) }
}
function exclude_coverage_stop_read_data_type() {} // solhint-disable-line no-empty-blocks
function exclude_coverage_start_case_const() {} // solhint-disable-line no-empty-blocks
function case_const(lhs, rhs) {
if sub(lhs, rhs) { err(ERR_INCORRECT_CASE_CONST) }
}
function exclude_coverage_stop_case_const() {} // solhint-disable-line no-empty-blocks
function exclude_coverage_start_err() {} // solhint-disable-line no-empty-blocks
function err(code) {
mstore(0, code)
revert(28, 4)
}
function exclude_coverage_stop_err() {} // solhint-disable-line no-empty-blocks
function exclude_coverage_start_read_entry() {} // solhint-disable-line no-empty-blocks
// slither-disable-start cyclomatic-complexity
function read_entry(result_ptr, data_type_variant) -> result_ptr_out, entry {
result_ptr_out := result_ptr
switch data_type_variant
case 0 {
case_const(0, DATA_TYPE_BOOLEAN_VARIANT)
entry := shr(BOOLEAN_PADDING_BITS, calldataload(result_ptr))
if shr(1, entry) { err(ERR_INVALID_BOOLEAN) }
result_ptr_out := add(result_ptr, BOOLEAN_SIZE)
entry := mod(entry, MODULUS)
}
case 2 {
case_const(2, DATA_TYPE_TINYINT_VARIANT)
entry :=
add(MODULUS, signextend(INT8_SIZE_MINUS_ONE, shr(INT8_PADDING_BITS, calldataload(result_ptr))))
result_ptr_out := add(result_ptr, INT8_SIZE)
entry := mod(entry, MODULUS)
}
case 3 {
case_const(3, DATA_TYPE_SMALLINT_VARIANT)
entry :=
add(MODULUS, signextend(INT16_SIZE_MINUS_ONE, shr(INT16_PADDING_BITS, calldataload(result_ptr))))
result_ptr_out := add(result_ptr, INT16_SIZE)
entry := mod(entry, MODULUS)
}
case 4 {
case_const(4, DATA_TYPE_INT_VARIANT)
entry :=
add(MODULUS, signextend(INT32_SIZE_MINUS_ONE, shr(INT32_PADDING_BITS, calldataload(result_ptr))))
result_ptr_out := add(result_ptr, INT32_SIZE)
entry := mod(entry, MODULUS)
}
case 5 {
case_const(5, DATA_TYPE_BIGINT_VARIANT)
entry :=
add(MODULUS, signextend(INT64_SIZE_MINUS_ONE, shr(INT64_PADDING_BITS, calldataload(result_ptr))))
result_ptr_out := add(result_ptr, INT64_SIZE)
entry := mod(entry, MODULUS)
}
case 7 {
case_const(7, DATA_TYPE_VARCHAR_VARIANT)
result_ptr_out, entry := read_binary(result_ptr)
}
case 8 {
case_const(8, DATA_TYPE_DECIMAL75_VARIANT)
entry := calldataload(result_ptr)
result_ptr_out := add(result_ptr, WORD_SIZE)
entry := mod(entry, MODULUS)
}
case 9 {
case_const(9, DATA_TYPE_TIMESTAMP_VARIANT)
entry :=
add(MODULUS, signextend(INT64_SIZE_MINUS_ONE, shr(INT64_PADDING_BITS, calldataload(result_ptr))))
result_ptr_out := add(result_ptr, INT64_SIZE)
entry := mod(entry, MODULUS)
}
case 10 {
case_const(10, DATA_TYPE_SCALAR_VARIANT)
entry := calldataload(result_ptr)
result_ptr_out := add(result_ptr, WORD_SIZE)
entry := mod(entry, MODULUS)
}
case 11 {
case_const(11, DATA_TYPE_VARBINARY_VARIANT)
result_ptr_out, entry := read_binary(result_ptr)
}
default { err(ERR_UNSUPPORTED_DATA_TYPE_VARIANT) }
}
// slither-disable-end cyclomatic-complexity
function exclude_coverage_stop_read_entry() {} // solhint-disable-line no-empty-blocks
function exclude_coverage_start_read_binary() {} // solhint-disable-line no-empty-blocks
function read_binary(result_ptr) -> result_ptr_out, entry {
let free_ptr := mload(FREE_PTR)
let len := shr(UINT64_PADDING_BITS, calldataload(result_ptr))
result_ptr := add(result_ptr, UINT64_SIZE)
// temps with their empty‐slice defaults
entry := 0
// only run this when len != 0
if len {
calldatacopy(free_ptr, result_ptr, len)
let hash_val := keccak256(free_ptr, len)
// endian-swap steps
hash_val :=
or(
shr(128, and(hash_val, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000)),
shl(128, and(hash_val, 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
)
hash_val :=
or(
shr(64, and(hash_val, 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000)),
shl(64, and(hash_val, 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF))
)
hash_val :=
or(
shr(32, and(hash_val, 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000)),
shl(32, and(hash_val, 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF))
)
hash_val :=
or(
shr(16, and(hash_val, 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000)),
shl(16, and(hash_val, 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF))
)
hash_val :=
or(
shr(8, and(hash_val, 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00)),
shl(8, and(hash_val, 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF))
)
entry := and(hash_val, MODULUS_MASK)
}
// single assign to named returns
result_ptr_out := add(result_ptr, len)
}
function exclude_coverage_stop_read_binary() {} // solhint-disable-line no-empty-blocks
let paramsOffset := add(serializedParams.offset, UINT64_SIZE)
let paramsArray := add(params, WORD_SIZE)
for {} length { length := sub(length, 1) } {
let data_type
paramsOffset, data_type := read_data_type(paramsOffset)
let entry
paramsOffset, entry := read_entry(paramsOffset, data_type)
mstore(paramsArray, entry)
paramsArray := add(paramsArray, WORD_SIZE)
}
}
}
/// @dev Serializes a bool parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function boolParam(bool param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_BOOLEAN_VARIANT, param);
}
/// @dev Serializes a tinyint parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function tinyIntParam(int8 param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_TINYINT_VARIANT, param);
}
/// @dev Serializes a smallint parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function smallIntParam(int16 param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_SMALLINT_VARIANT, param);
}
/// @dev Serializes an int32 parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function intParam(int32 param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_INT_VARIANT, param);
}
/// @dev Serializes a bigint parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function bigIntParam(int64 param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_BIGINT_VARIANT, param);
}
/// @dev Serializes a string parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function varCharParam(string memory param) internal pure returns (bytes memory serializedParam) {
uint64 length = uint64(bytes(param).length);
serializedParam = abi.encodePacked(DATA_TYPE_VARCHAR_VARIANT, length, param);
}
/// @dev Serializes a decimal parameter
/// @param param The parameter
/// @param precision The precision of the decimal
/// @param scale The scale of the decimal
/// @return serializedParam The serialized parameter
function decimal75Param(uint256 param, uint8 precision, int8 scale)
internal
pure
returns (bytes memory serializedParam)
{
serializedParam = abi.encodePacked(DATA_TYPE_DECIMAL75_VARIANT, precision, scale, param);
}
/// @dev Serializes a timestamp parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function unixTimestampMillisParam(int64 param) internal pure returns (bytes memory serializedParam) {
serializedParam =
abi.encodePacked(DATA_TYPE_TIMESTAMP_VARIANT, TIMEUNIT_MILLISECOND_VARIANT, TIMEZONE_UTC, param);
}
/// @dev Serializes a scalar parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function scalarParam(uint256 param) internal pure returns (bytes memory serializedParam) {
serializedParam = abi.encodePacked(DATA_TYPE_SCALAR_VARIANT, param);
}
/// @dev Serializes a varbinary parameter
/// @param param The parameter
/// @return serializedParam The serialized parameter
function varBinaryParam(bytes memory param) internal pure returns (bytes memory serializedParam) {
uint64 length = uint64(param.length);
serializedParam = abi.encodePacked(DATA_TYPE_VARBINARY_VARIANT, length, param);
}
}
"
},
"dependencies/sxt-proof-of-sql-0.123.10/src/client/PoSQLTable.post.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "../base/Constants.sol";
import "../base/Errors.sol";
/// @title ProofOfSqlTableUtilities
/// @dev Library for handling reading from a proof of sql table
library ProofOfSqlTable {
enum ColumnType {
Boolean,
// Not currently supported
Uint8,
TinyInt,
SmallInt,
Int,
BigInt,
// Not currently supported
Int128,
VarChar,
Decimal75,
TimeStampTZ,
Scalar,
VarBinary
}
struct Column {
string name;
ColumnType columnType;
// precision will simply be 0 if it is meaningless for a data type
uint8 precision;
// scale will simply be 0 if it is meaningless for a data type
int8 scale;
bytes data;
}
struct Table {
Column[] columns;
}
/// @notice Reads a result from a proof of sql query into the `Table` struct.
/// @custom:as-yul-wrapper
/// #### Wrapped Yul Function
/// ##### Signature
/// ```yul
/// function deserialize_from_bytes(serialized_table) -> table, serialized_table_out
/// ```
/// ##### Parameters
/// * `serialized_table` - The serialized table
/// ##### Return Values
/// * `table` - The deserialized table
/// * `serialized_table_out` - The data that remains after consuming the serialized table
/// @dev Reads a result from a proof of sql query into memory in a deserialized format.
/// @param __serializedTable The serialized table
/// @return __serializedTableOut The data that remains after consuming the serialized table
/// @return __table The deserialized table
function __deserializeFromBytes(bytes memory __serializedTable)
internal
pure
returns (bytes memory __serializedTableOut, Table memory __table)
{
assembly {
function exclude_coverage_start_err() {} // solhint-disable-line no-empty-blocks
function err(code) {
mstore(0, code)
revert(28, 4)
}
function exclude_coverage_stop_err() {} // solhint-disable-line no-empty-blocks
function read_column_type(column_data) -> column_type, precision, scale, column_data_out {
// Retrieve column type as uint8
column_type := shr(UINT32_PADDING_BITS, mload(column_data))
column_data := add(column_data, UINT32_SIZE)
// For decimals, scale and precision must be retrieved
if eq(column_type, DATA_TYPE_DECIMAL75_VARIANT) {
precision := byte(0, mload(column_data))
column_data := add(column_data, UINT8_SIZE)
scale := byte(0, mload(column_data))
column_data := add(column_data, INT8_SIZE)
}
if eq(column_type, DATA_TYPE_TIMESTAMP_VARIANT) {
// We only support milliseconds for timestamps, for now
let time_unit := shr(UINT32_PADDING_BITS, mload(column_data))
column_data := add(column_data, UINT32_SIZE)
if sub(time_unit, 1) { err(ERR_UNSUPPORTED_DATA_TYPE_VARIANT) }
// time unit is serialized by enum variant, so we need to adjust to the correct logical value
precision := 3
// We only support utc for timestamps, for now
let time_standard := shr(INT32_PADDING_BITS, mload(column_data))
column_data := add(column_data, INT32_SIZE)
if time_standard { err(ERR_UNSUPPORTED_DATA_TYPE_VARIANT) }
}
column_data_out := column_data
}
function get_byte_array_copy_size(source_ptr, column_length) -> copy_size {
// No need to retrieve the column length again
source_ptr := add(source_ptr, UINT64_SIZE)
for {} column_length { column_length := sub(column_length, 1) } {
// Per byte array, we will need to copy the number of bytes in the array plus the number of bytes needed to contain a uint64.
let byte_array_length := add(UINT64_SIZE, shr(UINT64_PADDING_BITS, mload(source_ptr)))
source_ptr := add(source_ptr, byte_array_length)
copy_size := add(copy_size, byte_array_length)
}
}
function get_column_as_bytes(source_ptr, column_type) -> source_ptr_out, column_as_bytes {
// Allocate space for the byte array
column_as_bytes := mload(FREE_PTR)
// Get length
let column_length := shr(UINT64_PADDING_BITS, mload(source_ptr))
// Determine how much space the column of data will take
let copy_size
switch column_type
// DATA_TYPE_BOOLEAN_VARIANT
case 0 { copy_size := mul(column_length, BOOLEAN_SIZE) }
// DATA_TYPE_TINYINT_VARIANT
case 2 { copy_size := mul(column_length, INT8_SIZE) }
// DATA_TYPE_SMALLINT_VARIANT
case 3 { copy_size := mul(column_length, INT16_SIZE) }
// DATA_TYPE_INT_VARIANT
case 4 { copy_size := mul(column_length, INT32_SIZE) }
// DATA_TYPE_BIGINT_VARIANT
case 5 { copy_size := mul(column_length, INT64_SIZE) }
// DATA_TYPE_VARCHAR_VARIANT
case 7 { copy_size := get_byte_array_copy_size(source_ptr, column_length) }
// DATA_TYPE_DECIMAL75_VARIANT
case 8 { copy_size := mul(column_length, WORD_SIZE) }
// DATA_TYPE_TIMESTAMP_VARIANT
case 9 { copy_size := mul(column_length, INT64_SIZE) }
// DATA_TYPE_SCALAR_VARIANT
case 10 { copy_size := mul(column_length, WORD_SIZE) }
// DATA_TYPE_VARBINARY_VARIANT
case 11 { copy_size := get_byte_array_copy_size(source_ptr, column_length) }
default { err(ERR_UNSUPPORTED_DATA_TYPE_VARIANT) }
// We need to include the length of the column of data in our serialized column
copy_size := add(copy_size, UINT64_SIZE)
// Save the length of the byte array
mstore(column_as_bytes, copy_size)
let target_ptr := add(column_as_bytes, WORD_SIZE)
// Copy the serialized column data into the byte array
for { let i := copy_size } i { i := sub(i, 1) } {
mstore8(target_ptr, byte(0, mload(source_ptr)))
source_ptr := add(source_ptr, 1)
target_ptr := add(target_ptr, 1)
}
mstore(FREE_PTR, target_ptr)
source_ptr_out := source_ptr
}
function get_byte_array(source_ptr) -> source_ptr_out, byte_array {
// Allocate space for the byte array
byte_array := mload(FREE_PTR)
// Find and store length of byte array
let len := shr(UINT64_PADDING_BITS, mload(source_ptr))
source_ptr := add(source_ptr, UINT64_SIZE)
mstore(byte_array, len)
let target_ptr := add(byte_array, WORD_SIZE)
// Copy bytes to byte array
for { let i := len } i { i := sub(i, 1) } {
mstore8(target_ptr, byte(0, mload(source_ptr)))
source_ptr := add(source_ptr, 1)
target_ptr := add(target_ptr, 1)
}
mstore(FREE_PTR, target_ptr)
source_ptr_out := source_ptr
}
function deserialize_column_from_bytes(serialized_column) -> column, serialized_column_out {
// Allocate memory for the column pointer
column := mload(FREE_PTR)
// Allocate space for the five fields
mstore(FREE_PTR, add(column, WORDX5_SIZE))
// Get and store the name
let name
serialized_column, name := get_byte_array(serialized_column)
mstore(column, name)
let target_ptr := add(column, WORD_SIZE)
// Check that column name is valid
// This is because an `Ident` from sqlparser 0.45.0
// has the field `quote_style` which must be 0 for unquoted identifiers.
if byte(0, mload(serialized_column)) { err(ERR_INVALID_RESULT_COLUMN_NAME) }
serialized_column := add(serialized_column, 1)
// Get and store type, precision, and scale
let column_type, precision, scale
column_type, precision, scale, serialized_column := read_column_type(serialized_column)
mstore(target_ptr, column_type)
target_ptr := add(target_ptr, WORD_SIZE)
mstore(target_ptr, precision)
target_ptr := add(target_ptr, WORD_SIZE)
mstore(target_ptr, scale)
target_ptr := add(target_ptr, WORD_SIZE)
// Get data and store in its serialized format
let column_as_bytes
serialized_column_out, column_as_bytes := get_column_as_bytes(serialized_column, column_type)
mstore(target_ptr, column_as_bytes)
}
function deserialize_from_bytes(serialized_table) -> table, serialized_table_out {
// Allocate memory for the table pointer
table := mload(FREE_PTR)
// Store column array pointer
let columns_field_ptr := add(table, WORD_SIZE)
mstore(table, columns_field_ptr)
// get and store number of columns
let num_columns := shr(UINT64_PADDING_BITS, mload(serialized_table))
serialized_table := add(serialized_table, UINT64_SIZE)
mstore(columns_field_ptr, num_columns)
columns_field_ptr := add(columns_field_ptr, WORD_SIZE)
// allocate space for each element
mstore(FREE_PTR, add(columns_field_ptr, mul(num_columns, WORD_SIZE)))
// populate and store each column pointer
for {} num_columns { num_columns := sub(num_columns, 1) } {
let column
column, serialized_table := deserialize_column_from_bytes(serialized_table)
mstore(columns_field_ptr, column)
columns_field_ptr := add(columns_field_ptr, WORD_SIZE)
}
serialized_table_out := serialized_table
}
__table, __serializedTableOut := deserialize_from_bytes(add(__serializedTable, WORD_SIZE))
}
}
/// @notice Deserializes a serialized column into memory.
/// @custom:as-yul-wrapper
/// #### Wrapped Yul Function
/// ##### Signature
/// ```yul
/// function return_pointer_to_typed_column_for_byte_array_element(column_as_bytes) -> column_ptr
/// ```
/// ##### Parameters
/// * `column_as_bytes` - The pointer to the column, serialized as bytes
/// ##### Return Values
/// * `column_ptr` - The pointer to the deserialized column
/// @dev Deserializes a serialized column into memory. The return value is meant to be used immediately, using yul,
/// to assign the deserialized column to a correctly typed variable.
/// @param __column The serialized column
/// @return __columnPtr The pointer to the deserialized column
function returnPointerToTypedColumnForByteArrayElements(Column memory __column)
internal
pure
returns (uint256 __columnPtr)
{
bytes memory __columnAsBytes = __column.data;
assembly {
function exclude_coverage_start_err() {} // solhint-disable-line no-empty-blocks
function err(code) {
mstore(0, code)
revert(28, 4)
}
function exclude_coverage_stop_err() {} // solhint-disable-line no-empty-blocks
function return_pointer_to_typed_column_for_byte_array_element(column_as_bytes) -> column_ptr {
column_as_bytes := add(column_as_bytes, WORD_SIZE)
column_ptr := mload(FREE_PTR)
// Find and store length of column
let column_length := shr(UINT64_PADDING_BITS, mload(column_as_bytes))
column_as_bytes := add(column_as_bytes, UINT64_SIZE)
mstore(column_ptr, column_length)
let target_ptr := add(column_ptr, WORD_SIZE)
// Allocate space for the pointer of each byte array element
let free_ptr := add(target_ptr, mul(column_length, WORD_SIZE))
// We process one byte array at a time
for {} column_length { column_length := sub(column_length, 1) } {
// Store the next pointer in the column array
mstore(target_ptr, free_ptr)
target_ptr := add(target_ptr, WORD_SIZE)
// Find and store the length of the byte array
let len := shr(UINT64_PADDING_BITS, mload(column_as_bytes))
column_as_bytes := add(column_as_bytes, UINT64_SIZE)
mstore(free_ptr, len)
free_ptr := add(free_ptr, WORD_SIZE)
// Copy over each byte into the new byte array
for {} gt(len, WORD_SIZE) { len := sub(len, WORD_SIZE) } {
mstore(free_ptr, mload(column_as_bytes))
column_as_bytes := add(column_as_bytes, WORD_SIZE)
free_ptr := add(free_ptr, WORD_SIZE)
}
let remaining_bytes := mul(8, sub(WORD_SIZE, len))
mstore(free_ptr, shl(remaining_bytes, shr(remaining_bytes, mload(column_as_bytes))))
column_as_bytes := add(column_as_bytes, len)
free_ptr := add(free_ptr, len)
}
mstore(FREE_PTR, free_ptr)
}
__columnPtr := return_pointer_to_typed_column_for_byte_array_element(__columnAsBytes)
}
}
/// @notice Deserializes a serialized column into memory.
/// @custom:as-yul-wrapper
/// #### Wrapped Yul Function
/// ##### Signature
/// ```yul
/// function return_pointer_to_typed_column_for_fixed_sized_element(column_as_bytes, element_size) -> column_ptr
/// ```
/// ##### Parameters
/// * `column_as_bytes` - The pointer to the column, serialized as bytes
/// * `element_size` - The size of the fixed size elements
/// ##### Return Values
/// * `column_ptr` - The pointer to the deserialized column
/// @dev Deserializes a serialized column into memory. The return value is meant to be used immediately, using yul,
/// to assign the deserialized column to a correctly typed variable.
/// @param __column The serialized column of data
/// @param __elementSize The size of the fixed size elements
/// @return __columnPtr The pointer to the deserialized column
function returnPointerToTypedColumnForFixedSizeElement(Column memory __column, uint256 __elementSize)
internal
pure
returns (uint256 __columnPtr)
{
bytes memory __columnAsBytes = __column.data;
assembly {
function exclude_coverage_start_err() {} // solhint-disable-line no-empty-blocks
function err(code) {
mstore(0, code)
revert(28, 4)
}
function exclude_coverage_stop_err() {} // solhint-disable-line no-empty-blocks
function return_pointer_to_typed_column_for_fixed_sized_element(column_as_bytes, element_size) -> column_ptr
{
column_as_bytes := add(column_as_bytes, WORD_SIZE)
column_ptr := mload(FREE_PTR)
// Find and store length of column
let column_length := shr(UINT64_PADDING_BITS, mload(column_as_bytes))
column_as_bytes := add(column_as_bytes, UINT64_SIZE)
mstore(column_ptr, column_length)
let target_ptr := add(column_ptr, WORD_SIZE)
// Calculate the number of bits to shift the 32 byte value loaded from memory in order to retrieve the next array element
let element_padding_bits := mul(8, sub(WORD_SIZE, element_size))
// Copy each element into the new column
for {} column_length { column_length := sub(column_length, 1) } {
mstore(target_ptr, shr(element_padding_bits, mload(column_as_bytes)))
column_as_bytes := add(column_as_bytes, element_size)
target_ptr := add(target_ptr, WORD_SIZE)
}
mstore(FREE_PTR, target_ptr)
}
__columnPtr := return_pointer_to_typed_column_for_fixed_sized_element(__columnAsBytes, __elementSize)
}
}
/// @dev Deserializes a column into a boolean column.
/// @param __table The table
/// @param __index The index of the column to be deserialized
/// @return __booleanColumn The deserialized boolean column
function readBooleanColumn(Table memory __table, uint256 __index)
internal
pure
returns (bool[] memory __booleanColumn)
{
Column memory __column = __table.columns[__index];
assert(__column.columnType == ColumnType.Boolean);
uint256 __columnPtr = returnPointerToTypedColumnForFixedSizeElement(__column, BOOLEAN_SIZE);
assembly {
// We assign the return value here because the pointer is not properly typed within the solidity
__booleanColumn := __columnPtr
}
}
/// @dev Deserializes a column into a tinyint column.
/// @param __table The table
/// @param __index The index of the column to be deserialized
/// @return __tinyIntColumn The deserialized tinyint column
function readTinyIntColumn(Table memory __table, uint256 __index)
internal
pure
returns (int8[] memory __tinyIntColumn)
{
Column memory __column = __table.columns[__index];
assert(__column.columnType == ColumnType.TinyInt);
uint256 __columnPtr = returnPointerToTypedColumnForFixedSizeElement(__column, INT8_SIZE);
assembly {
__tinyIntColumn := __columnPtr
}
}
/// @dev Deserializes a column into a smallint column.
/// @param __table The table
/// @param __index The index of the column to be deserialized
/// @return __smallIntColumn The deserialized smallint column
function readSmallIntColumn(Table memory __table, uint256 __index)
internal
pure
returns (int16[] memory __smallIntColumn)
{
Column memory __column = __table.columns[__index];
assert(__column.columnType == ColumnType.SmallInt);
uint256 __columnPtr = returnPointerToTypedColumnForFixedSize
Submitted on: 2025-11-06 20:38:29
Comments
Log in to comment.
No comments yet.