Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registration relayer #2

Closed
wants to merge 12 commits into from
Closed
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node: ['16.x', '18.x']
node: ['18.x']
os: [ubuntu-latest]

steps:
Expand Down
17 changes: 17 additions & 0 deletions packages/contracts/contracts/relayer/evm/Controllable.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/access/Ownable.sol";

abstract contract Controllable is Ownable {
mapping(address => bool) public controllers;

modifier onlyController {
require(controllers[msg.sender]);
_;
}

function setController(address controller, bool status) external onlyOwner {
controllers[controller] = status;
}
}
93 changes: 93 additions & 0 deletions packages/contracts/contracts/relayer/evm/RegistrationProxy.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/access/Ownable.sol";
import "./Controllable.sol";

contract RegistrationProxy is Ownable, Controllable {
enum Status {
NON_EXISTENT,
PENDING,
SUCCESS,
FAILURE
}

event InitiateRequest(
uint256 indexed id,
string name,
string recipient,
uint8 yearsToRegister,
uint256 value,
uint256 ttl
);

event ResultInfo(
uint256 indexed id,
bool success,
uint256 refundAmt
);

struct Record {
// string name;
address initiator;
uint256 value;
uint256 ttl;
Status status;
}

uint256 public id;
uint256 public holdPeriod;
mapping(uint256 => Record) public idToRecord;

constructor(uint256 _holdPeriod) Ownable() {
holdPeriod = _holdPeriod;
}

function setHoldPeriod(uint256 _holdPeriod) external onlyOwner {
holdPeriod = _holdPeriod;
}

function register(
string calldata name,
string calldata recipient,
uint8 yearsToRegister
) external payable {
uint256 ttl = block.timestamp + holdPeriod;
uint256 _id = id++;

idToRecord[_id] = Record(msg.sender, msg.value, ttl, Status.PENDING);

emit InitiateRequest(
_id,
name,
recipient,
yearsToRegister,
msg.value,
ttl
);
}

function success(uint256 _id, uint256 refundAmt) external onlyController {
Record memory record = idToRecord[_id];
require(record.status == Status.PENDING, "Invalid state");
require(refundAmt <= record.value, "Refund exceeds received value");

record.status = Status.SUCCESS;
idToRecord[_id] = record;
payable(record.initiator).transfer(refundAmt);

emit ResultInfo(_id, true, refundAmt);
}

function failure(uint256 _id) external {
Record memory record = idToRecord[_id];
require(record.status == Status.PENDING, "Invalid state");
require(controllers[msg.sender] || record.ttl < block.timestamp, "Only controller can respond till TTL");

record.status = Status.FAILURE;
idToRecord[_id] = record;
payable(record.initiator).transfer(record.value);

emit ResultInfo(_id, false, record.value);
}
}
9 changes: 9 additions & 0 deletions packages/contracts/contracts/relayer/wasm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Ignore build artifacts from the local tests sub-crate.
/target/

# Ignore backup files creates by cargo fmt.
**/*.rs.bk

# Remove Cargo.lock when creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
23 changes: 23 additions & 0 deletions packages/contracts/contracts/relayer/wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "wasm"
version = "0.1.0"
authors = ["[your_name] <[your_email]>"]
edition = "2021"

[dependencies]
ink = { version = "5.0.0", default-features = false }
zink = { git = "https://github.com/scio-labs/zink" }

[dev-dependencies]
ink_e2e = { version = "5.0.0" }

[lib]
path = "lib.rs"

[features]
default = ["std"]
std = [
"ink/std",
]
ink-as-dependency = []
e2e-tests = []
169 changes: 169 additions & 0 deletions packages/contracts/contracts/relayer/wasm/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
#![cfg_attr(not(feature = "std"), no_std, no_main)]

#[zink::coating(Ownable2Step[
Error = Error::NotAdmin
])]
#[ink::contract]
mod registration_proxy {
use ink::env::call::{build_call, ExecutionInput, Selector};
use ink::prelude::string::String;
use ink::storage::Mapping;

#[ink(event)]
pub struct Success {
id: u128,
price: Balance,
}

#[ink(storage)]
pub struct RegistrationProxy {
admin: AccountId,
/// Two-step ownership transfer AccountId
pending_admin: Option<AccountId>,
registry_addr: AccountId,
controllers: Mapping<AccountId, ()>,
}

#[derive(Debug)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
pub enum Error {
/// Caller not allowed to call privileged calls.
NotAdmin,
/// Caller is not approved as controller
NotController,
/// Insufficient balance in the contract
InsufficientBalance,
/// Price exceeds the mentioned cap
TooExpensive,
/// Failed to register
RegisterFailed(u8),
/// Unable to retrieve the price
PriceFetchFailed(u8),
}

impl RegistrationProxy {
#[ink(constructor)]
pub fn new(admin: AccountId, registry_addr: AccountId) -> Self {
Self {
admin,
pending_admin: None,
registry_addr,
controllers: Mapping::default(),
}
}

#[ink(message, payable)]
pub fn fund_me(&mut self) -> Result<(), Error> {
Ok(())
}

#[ink(message)]
pub fn register(
&mut self,
id: u128,
name: String,
recipient: AccountId,
years_to_register: u8,
max_fees: Balance,
) -> Result<Balance, Error> {
self.ensure_controller()?;

let price = self.get_name_price(&name, recipient, years_to_register)?;
if price > max_fees {
return Err(Error::TooExpensive);
} else if price > self.env().balance() {
return Err(Error::InsufficientBalance);
}

const REGISTER_SELECTOR: [u8; 4] = ink::selector_bytes!("register_on_behalf_of");
let result = build_call::<Environment>()
.call(self.registry_addr)
.call_v1()
.exec_input(
ExecutionInput::new(Selector::new(REGISTER_SELECTOR))
.push_arg(name)
.push_arg(recipient)
.push_arg(years_to_register)
.push_arg::<Option<String>>(None)
.push_arg::<Option<String>>(None),
)
.returns::<core::result::Result<(), u8>>()
.transferred_value(price)
.params()
.invoke();

result.map_err(Error::RegisterFailed)?;

self.env().emit_event(Success {
id,
price,
});

Ok(price)
}

#[ink(message)]
pub fn set_controller(&mut self, controller: AccountId, enable: bool) -> Result<(), Error> {
self.ensure_admin().expect("Not Authorised");

if enable {
self.controllers.insert(controller, &());
} else {
self.controllers.remove(controller);
}

Ok(())
}

#[ink(message)]
pub fn is_controller(&self, controller: AccountId) -> bool {
self.controllers.contains(controller)
}

#[ink(message)]
pub fn upgrade_contract(&mut self, code_hash: Hash) {
self.ensure_admin().expect("Not Authorised");

self.env().set_code_hash(&code_hash).unwrap_or_else(|err| {
panic!(
"Failed to `set_code_hash` to {:?} due to {:?}",
code_hash, err
)
});
ink::env::debug_println!("Switched code hash to {:?}.", code_hash);
}

fn get_name_price(
&self,
name: &str,
recipient: AccountId,
years_to_register: u8,
) -> Result<Balance, Error> {
const GET_NAME_PRICE_SELECTOR: [u8; 4] = ink::selector_bytes!("get_name_price");

let result = build_call::<Environment>()
.call(self.registry_addr)
.call_v1()
.exec_input(
ExecutionInput::new(Selector::new(GET_NAME_PRICE_SELECTOR))
.push_arg(name)
.push_arg(recipient)
.push_arg(years_to_register)
.push_arg::<Option<String>>(None),
)
.returns::<core::result::Result<(Balance, Balance, Balance, Option<AccountId>), u8>>()
.params()
.invoke();

let (base_price, premium, _, _) = result.map_err(Error::PriceFetchFailed)?;
let price = base_price.checked_add(premium).expect("Overflow");

Ok(price)
}

fn ensure_controller(&self) -> Result<(), Error> {
let caller = self.env().caller();
self.controllers.get(caller).ok_or(Error::NotController)
}
}
}
10 changes: 10 additions & 0 deletions packages/gateway/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
PORT=8080
TTL=300
WASM_PROVIDER_URL='wss://ws.test.azero.dev'
EVM_PROVIDER_URL='https://ethereum-sepolia.publicnode.com'
EVM_RELAYER_CONTRACT='0x2BaD727319377af238a7F6D166494118Ca9D0497'
WASM_RELAYER_CONTRACT='5GNDka5xV9y9nsES2gqYQponJ8vJaAmoJjMUvrqGqPF65q7P'
BUFFER_DURATION_IN_MIN= 10
GATEWAY_SIGNER_KEY=
EVM_PRIVATE_KEY=
WASM_PRIVATE_KEY=
Loading
Loading