Skip to content

Commit

Permalink
Improve contracts & relayer
Browse files Browse the repository at this point in the history
  • Loading branch information
SecretSaturn committed Jan 20, 2024
1 parent 8b713c0 commit cee5881
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 78 deletions.
6 changes: 3 additions & 3 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
[submodule "public-gateway/lib/solmate"]
path = public-gateway/lib/solmate
url = https://github.com/transmissions11/solmate
[submodule "TNLS-Gateways/public-gateway/lib/openzeppelin-contracts"]
path = TNLS-Gateways/public-gateway/lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
[submodule "TNLS-Gateways/public-gateway/lib/openzeppelin-contracts-upgradeable"]
path = TNLS-Gateways/public-gateway/lib/openzeppelin-contracts-upgradeable
url = https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable
2 changes: 1 addition & 1 deletion TNLS-Clients/payload-encryption/src/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function setupSubmit(element: HTMLButtonElement) {
element.addEventListener("click", async function(event: Event){
event.preventDefault()
const [myAddress] = await provider.send("eth_requestAccounts", []);
await window.ethereum.request({
await (window as any).ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xAA36A7' }], // chainId must be in hexadecimal numbers
});
Expand Down
12 changes: 0 additions & 12 deletions TNLS-Gateways/node_modules/.yarn-integrity

This file was deleted.

1 change: 0 additions & 1 deletion TNLS-Gateways/public-gateway/foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ libs = ['lib']
auto_detect_solc = true
fs_permissions = [{ access = "read", path = "./"}]
build_info = true
extra_output = ["storageLayout"]

[fmt]
line_length = 150
Expand Down
1 change: 0 additions & 1 deletion TNLS-Gateways/public-gateway/lib/openzeppelin-contracts
Submodule openzeppelin-contracts deleted from 281ab1
34 changes: 34 additions & 0 deletions TNLS-Gateways/public-gateway/script/DeployRandomnessScript.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.23;

import "forge-std/Test.sol";
import "forge-std/Vm.sol";
import "forge-std/console2.sol";
import "forge-std/Script.sol";
import {Gateway} from "../src/Gateway.sol";
import {RandomnessReciever} from "../src/RandomnessReciever.sol";



contract DeployRandomnessScript is Script {
function setUp() public {}

address deployer;
RandomnessReciever randomnessAddress;

uint256 privKey = vm.envUint("ETH_PRIVATE_KEY");


function run() public {
deployer = vm.rememberKey(privKey);
vm.startBroadcast();

Gateway gateway = Gateway(0x5e1e92eA6A1b7a58D88619C625FEc5D27147bc64);
randomnessAddress = new RandomnessReciever();
console2.logAddress(address(randomnessAddress));

randomnessAddress.setGatewayAddress(address(gateway));

vm.stopBroadcast();
}
}
4 changes: 2 additions & 2 deletions TNLS-Gateways/public-gateway/script/UpgradeScript.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ contract UpgradeScript is Script {
// Deploy New Gateway Logic Contract
newGatewayLogic = new Gateway();

gatewayProxyAdmin = ProxyAdmin(0x9eA72D83533D8B753d000D9C233a80CC08FFb072);
gatewayProxyAdmin = ProxyAdmin(0x5B7191206b913F892956d7880C041dc1A764016C);

bytes memory selector = abi.encodeWithSelector(Gateway.upgradeHandler.selector);
gatewayProxyAdmin.upgradeAndCall(ITransparentUpgradeableProxy(0x286B1e6B58a913E457509f0C30Ad4393C78f4F84), address(newGatewayLogic),selector);
gatewayProxyAdmin.upgradeAndCall(ITransparentUpgradeableProxy(0x5e1e92eA6A1b7a58D88619C625FEc5D27147bc64), address(newGatewayLogic),selector);

vm.stopBroadcast();
}
Expand Down
67 changes: 18 additions & 49 deletions TNLS-Gateways/public-gateway/src/Gateway.sol
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.23;

import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";


/*//////////////////////////////////////////////////////////////
Gateway Proxy
//////////////////////////////////////////////////////////////*/
contract GatewayProxy is TransparentUpgradeableProxy {
constructor(address _logic, address admin_, bytes memory _data) TransparentUpgradeableProxy(_logic, admin_, _data) {}
}

contract Gateway is Initializable {
contract Gateway is Initializable, OwnableUpgradeable {
/*//////////////////////////////////////////////////////////////
Constants
//////////////////////////////////////////////////////////////*/

//Use hard coded constant values instead of storage variables for Secret VRF, saves around 10,000+ in gas per TX.
//Since contract is upgradeable, we can update these values as well with it.

bytes constant routing_info = "secret14hlku6qen0tkhfq0cklx02hcdu9jph8un4lsga";
bytes constant routing_code_hash = "ba0006753cb18a8b12fe266707289098bfb8a3ae83de54ecece591231ada2abf";
string constant task_destination_network = "secret-4";
address constant secret_gateway_signer_address = 0x1b153e8fc101c2c6C9e0a9250aca99e957354a8E;


/*//////////////////////////////////////////////////////////////
Structs
//////////////////////////////////////////////////////////////*/
Expand Down Expand Up @@ -61,7 +54,6 @@ contract Gateway is Initializable {
State Variables
//////////////////////////////////////////////////////////////*/

address public owner;
uint256 public taskId;

/// @dev Task ID ====> Task
Expand All @@ -86,9 +78,6 @@ contract Gateway is Initializable {
/// @notice thrown when the Task was already completed
error TaskAlreadyCompleted();

/// @notice thrown when the Callback failed
error CallbackError();

/// @notice thrown when the Bytes Length is not a multiple of 32 bytes
error InvalidBytesLength();

Expand Down Expand Up @@ -128,7 +117,7 @@ contract Gateway is Initializable {
/// @param _signature The signature
/// @return The address of the signer

function recoverSigner(bytes32 _signedMessageHash, bytes memory _signature) private pure returns (address) {
function recoverSigner(bytes32 _signedMessageHash, bytes calldata _signature) private pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_signedMessageHash, v, r, s);
}
Expand Down Expand Up @@ -238,29 +227,24 @@ contract Gateway is Initializable {
ExecutionInfo info
);

/// @notice Emitted when we recieve callback for our result of the computation
event ComputedResult(uint256 taskId, bytes result);
/// @notice Emitted when the callback was completed
event TaskCompleted(uint256 taskId, bool callbackSuccessful);

/*//////////////////////////////////////////////////////////////
Modifiers
//////////////////////////////////////////////////////////////*/

modifier onlyOwner() {
require(msg.sender == owner, "UNAUTHORIZED");
_;
}

/*//////////////////////////////////////////////////////////////
Initializer
//////////////////////////////////////////////////////////////*/

/// @notice Replaces the constructor for upgradeable contracts

function initialize() public initializer {
owner = msg.sender;
__Ownable_init(msg.sender);
taskId = 1;
}

constructor() {
_disableInitializers();
}

/*//////////////////////////////////////////////////////////////
Maintainance Functions
//////////////////////////////////////////////////////////////*/
Expand All @@ -276,7 +260,7 @@ contract Gateway is Initializable {
/// @notice Payout the paid balance to the owner

function payoutBalance() external onlyOwner {
payable(owner).transfer(address(this).balance);
payable(owner()).transfer(address(this).balance);
}

/*//////////////////////////////////////////////////////////////
Expand All @@ -287,7 +271,7 @@ contract Gateway is Initializable {
/// @param _callbackGasLimit the Callback Gas Limit

function estimateRequestPrice(uint32 _callbackGasLimit) private view returns (uint256) {
uint256 baseFee = _callbackGasLimit*tx.gasprice;
uint256 baseFee = _callbackGasLimit*block.basefee;
return baseFee;
}

Expand All @@ -307,7 +291,8 @@ contract Gateway is Initializable {
string calldata _routingInfo,
ExecutionInfo calldata _info)
external payable {


//checks if enough gas was paid
if (estimateRequestPrice(_info.callback_gas_limit) > msg.value) {
revert PaidRequestFeeTooLow();
}
Expand Down Expand Up @@ -354,6 +339,7 @@ contract Gateway is Initializable {
revert TooManyVRFRandomWordsRequested();
}

//checks if enough gas was paid for callback
if (estimateRequestPrice(_callbackGasLimit) > msg.value) {
revert PaidRequestFeeTooLow();
}
Expand All @@ -363,8 +349,7 @@ contract Gateway is Initializable {

//construct the payload that is sent into the Secret Gateway
bytes memory payload = bytes.concat(
'{"data":"{\\"numWords\\":',
bytes(uint256toString(_numWords)),
'{"data":"{\\"numWords\\":',bytes(uint256toString(_numWords)),
'}","routing_info": "',routing_info,
'","routing_code_hash": "',routing_code_hash,
'","user_address": "0x0000000000000000000000000000000000000000","user_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",', //unused user_address here + 33 bytes of zeros in base64 for user_key
Expand Down Expand Up @@ -468,29 +453,13 @@ contract Gateway is Initializable {
abi.encodeWithSelector(_info.callback_selector, _taskId, _info.result)
);
}
if (!callbackSuccessful) {
revert CallbackError();
}
}

/*//////////////////////////////////////////////////////////////
Callback
//////////////////////////////////////////////////////////////*/

/// @notice Emits an event with the result of a computation
/// @param _taskId The ID of the task
/// @param _result The result of the computation

function callback(uint256 _taskId, bytes calldata _result) external {
emit ComputedResult(_taskId, _result);
emit TaskCompleted(_taskId, callbackSuccessful);
}

/*//////////////////////////////////////////////////////////////
New Functions for Upgradeability
//////////////////////////////////////////////////////////////*/
event contractUpgraded();

function upgradeHandler() public {
emit contractUpgraded();
}
}
27 changes: 20 additions & 7 deletions TNLS-Gateways/public-gateway/src/RandomnessReciever.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,38 @@ contract RandomnessReciever {

/// @notice Event that is emitted when a VRF call was made (optional)
/// @param requestId requestId of the VRF request. Contract can track a VRF call that way
event requestRandomness(uint256 requestId);
event requestedRandomness(uint256 requestId);

/// @notice Demo function on how to implement a VRF call using Secret VRF
function requestRandomnessTest() external {
function requestRandomnessTest(uint32 _numWords, uint32 _callbackGasLimit) external payable {
// Get the VRFGateway contract interface
ISecretVRF vrfContract = ISecretVRF(VRFGateway);

// Call the VRF contract to request random numbers.
// Returns requestId of the VRF request. A contract can track a VRF call that way.
uint256 requestId = vrfContract.requestRandomness{value: msg.value}(_numWords, _callbackGasLimit);

// Emit the event
emit requestedRandomness(requestId);
}

/// @notice Demo function on how to implement a VRF call using Secret VRF, here the values for numWords and callbackGasLimit are preset
function requestRandomnessTestPreset() external payable {
// Can be up to 2000 random numbers, change this according to your needs
uint32 numWords = 10;
uint32 numWords = 20;

// Change callbackGasLimit according to your needs for post processing in your callback
uint32 callbackGasLimit = 2000000;
uint32 callbackGasLimit = 300000;

// Get the VRFGateway contrac interface
// Get the VRFGateway contract interface
ISecretVRF vrfContract = ISecretVRF(VRFGateway);

// Call the VRF contract to request random numbers.
// Returns requestId of the VRF request. A contract can track a VRF call that way.
uint256 requestId = vrfContract.requestRandomness(numWords, callbackGasLimit);
uint256 requestId = vrfContract.requestRandomness{value: msg.value}(numWords, callbackGasLimit);

// Emit the event
emit requestRandomness(requestId);
emit requestedRandomness(requestId);
}

/*//////////////////////////////////////////////////////////////
Expand Down
2 changes: 1 addition & 1 deletion config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
type: evm
chain_id: "11155111"
api_endpoint: https://sepolia.gateway.tenderly.co
contract_address: "0x286B1e6B58a913E457509f0C30Ad4393C78f4F84"
contract_address: "0x5e1e92eA6A1b7a58D88619C625FEc5D27147bc64"
contract_schema: '[{"type":"function","name":"callback","inputs":[{"name":"_taskId","type":"uint256","internalType":"uint256"},{"name":"_result","type":"bytes","internalType":"bytes"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"estimateRequestPrice","inputs":[{"name":"_callbackGasLimit","type":"uint32","internalType":"uint32"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"increaseTaskId","inputs":[{"name":"_newTaskId","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"initialize","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"owner","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"payoutBalance","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"postExecution","inputs":[{"name":"_taskId","type":"uint256","internalType":"uint256"},{"name":"_sourceNetwork","type":"string","internalType":"string"},{"name":"_info","type":"tuple","internalType":"struct Gateway.PostExecutionInfo","components":[{"name":"payload_hash","type":"bytes32","internalType":"bytes32"},{"name":"packet_hash","type":"bytes32","internalType":"bytes32"},{"name":"callback_address","type":"bytes20","internalType":"bytes20"},{"name":"callback_selector","type":"bytes4","internalType":"bytes4"},{"name":"callback_gas_limit","type":"bytes4","internalType":"bytes4"},{"name":"packet_signature","type":"bytes","internalType":"bytes"},{"name":"result","type":"bytes","internalType":"bytes"}]}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"requestRandomness","inputs":[{"name":"_numWords","type":"uint32","internalType":"uint32"},{"name":"_callbackGasLimit","type":"uint32","internalType":"uint32"}],"outputs":[{"name":"requestId","type":"uint256","internalType":"uint256"}],"stateMutability":"payable"},{"type":"function","name":"send","inputs":[{"name":"_payloadHash","type":"bytes32","internalType":"bytes32"},{"name":"_userAddress","type":"address","internalType":"address"},{"name":"_callbackGasLimit","type":"uint32","internalType":"uint32"},{"name":"_routingInfo","type":"string","internalType":"string"},{"name":"_info","type":"tuple","internalType":"struct Gateway.ExecutionInfo","components":[{"name":"user_key","type":"bytes","internalType":"bytes"},{"name":"user_pubkey","type":"bytes","internalType":"bytes"},{"name":"routing_code_hash","type":"string","internalType":"string"},{"name":"task_destination_network","type":"string","internalType":"string"},{"name":"handle","type":"string","internalType":"string"},{"name":"nonce","type":"bytes12","internalType":"bytes12"},{"name":"callback_gas_limit","type":"uint32","internalType":"uint32"},{"name":"payload","type":"bytes","internalType":"bytes"},{"name":"payload_signature","type":"bytes","internalType":"bytes"}]}],"outputs":[],"stateMutability":"payable"},{"type":"function","name":"taskId","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"tasks","inputs":[{"name":"","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"payload_hash_reduced","type":"bytes31","internalType":"bytes31"},{"name":"completed","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"type":"function","name":"upgradeHandler","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"type":"event","name":"ComputedResult","inputs":[{"name":"taskId","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"result","type":"bytes","indexed":false,"internalType":"bytes"}],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"name":"version","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"type":"event","name":"contractUpgraded","inputs":[],"anonymous":false},{"type":"event","name":"logNewTask","inputs":[{"name":"task_id","type":"uint256","indexed":true,"internalType":"uint256"},{"name":"source_network","type":"string","indexed":false,"internalType":"string"},{"name":"user_address","type":"address","indexed":false,"internalType":"address"},{"name":"routing_info","type":"string","indexed":false,"internalType":"string"},{"name":"payload_hash","type":"bytes32","indexed":false,"internalType":"bytes32"},{"name":"info","type":"tuple","indexed":false,"internalType":"struct Gateway.ExecutionInfo","components":[{"name":"user_key","type":"bytes","internalType":"bytes"},{"name":"user_pubkey","type":"bytes","internalType":"bytes"},{"name":"routing_code_hash","type":"string","internalType":"string"},{"name":"task_destination_network","type":"string","internalType":"string"},{"name":"handle","type":"string","internalType":"string"},{"name":"nonce","type":"bytes12","internalType":"bytes12"},{"name":"callback_gas_limit","type":"uint32","internalType":"uint32"},{"name":"payload","type":"bytes","internalType":"bytes"},{"name":"payload_signature","type":"bytes","internalType":"bytes"}]}],"anonymous":false},{"type":"error","name":"CallbackError","inputs":[]},{"type":"error","name":"InvalidBytesLength","inputs":[]},{"type":"error","name":"InvalidInitialization","inputs":[]},{"type":"error","name":"InvalidPacketSignature","inputs":[]},{"type":"error","name":"InvalidPayloadHash","inputs":[]},{"type":"error","name":"InvalidSignature","inputs":[]},{"type":"error","name":"InvalidSignatureLength","inputs":[]},{"type":"error","name":"NotInitializing","inputs":[]},{"type":"error","name":"PaidRequestPriceTooLow","inputs":[]},{"type":"error","name":"TaskAlreadyCompleted","inputs":[]},{"type":"error","name":"TooManyVRFRandomWordsRequested","inputs":[]}]'
wallet_address: "0xbb6B8abe049466f637b3Ac648E7Dd9850E193346"

Expand Down
3 changes: 2 additions & 1 deletion remappings.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
ds-test/=public-gateway/lib/forge-std/lib/ds-test/src/
forge-std/=public-gateway/lib/forge-std/src/
openzeppelin-contracts/=public-gateway/lib/openzeppelin-contracts
@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/
@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/
solmate/=public-gateway/lib/solmate/src/

0 comments on commit cee5881

Please sign in to comment.