Skip to content

Commit

Permalink
merge latest from Sven and change to RequestSuccess
Browse files Browse the repository at this point in the history
  • Loading branch information
ltfschoen committed Oct 9, 2024
1 parent fc87e25 commit c988c58
Show file tree
Hide file tree
Showing 10 changed files with 251 additions and 80 deletions.
20 changes: 10 additions & 10 deletions packages/hardhat/contracts/NunyaBusiness.sol
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ contract NunyaBusiness {
mapping (uint256 => FunctionCallType) expectedResult;

event ReceiptEmitted(Receipt);
event Request_success(uint256 requestId);
event RequestSuccess(uint256 requestId);
event SecretNetworkError(uint256 requestId, string message);
event HackingAttemptError(uint256 requestId);

Expand Down Expand Up @@ -78,7 +78,7 @@ contract NunyaBusiness {
require (expectedResult[_requestId]==FunctionCallType.NEW_USER);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - duplicate user?");
emit Request_success(_requestId);
emit RequestSuccess(_requestId);
}

// Function wrapped in secret network payload encryption
Expand All @@ -93,23 +93,23 @@ contract NunyaBusiness {
require (expectedResult[_requestId]==FunctionCallType.NEW_REF);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - no user found?");
emit Request_success(_requestId);
emit RequestSuccess(_requestId);
}

// TODO: use ref encrypted with (user pubkey+salt)
function pay(string calldata _ref, uint256 _value) public payable returns (uint256) {
function pay(string calldata _ref, uint256 _amount) public payable returns (uint256) {
// >= because we need gas for
require (_value >= msg.value, "Naughty!");
require (_amount >= msg.value, "Naughty!");
uint256 gasPaid = fundGateway();
uint256 requestId = secretContract.pay(_ref, msg.value-gasPaid);
expectedResult[requestId]=FunctionCallType.PAY;
return(requestId);
}

// TODO: use ref encrypted with (user pubkey+salt)
function pay(string calldata _ref, uint256 _value, uint256 _userPubkey) public payable returns (uint256) {
function pay(string calldata _ref, uint256 _amount, uint256 _userPubkey) public payable returns (uint256) {
// >= because we need gas for
require (_value >= msg.value, "Naughty!");
require (_amount >= msg.value, "Naughty!");
uint256 gasPaid = fundGateway();
uint256 requestId = secretContract.payWithReceipt(_ref, msg.value-gasPaid, _userPubkey);
expectedResult[requestId]=FunctionCallType.PAY;
Expand Down Expand Up @@ -137,7 +137,7 @@ contract NunyaBusiness {
require (expectedResult[_requestId]==FunctionCallType.PAY);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - wrong payment ref?");
emit Request_success(_requestId);
emit RequestSuccess(_requestId);
}

function payCallback(uint256 _requestId, bool _success, Receipt calldata _receipt) public payable onlyGateway {
Expand All @@ -147,7 +147,7 @@ contract NunyaBusiness {
emit SecretNetworkError(_requestId, "Error paying - wrong payment ref?");
if (uint256(_receipt.sig)!=0)
emit ReceiptEmitted(_receipt);
emit Request_success(_requestId);
emit RequestSuccess(_requestId);
}

receive() external payable {
Expand All @@ -170,7 +170,7 @@ contract NunyaBusiness {
emit SecretNetworkError(_requestId, "Error withdrawing - out of funds?");
require(_amount > 0, "Account not found or empty.");
_withdrawalAddress.transfer(_amount);
emit Request_success(_requestId);
emit RequestSuccess(_requestId);
}

function emitSecretNetworkError(uint256 _requestId, string memory _message) public onlyGateway {
Expand Down
177 changes: 177 additions & 0 deletions packages/hardhat/contracts/payWithEth.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// TODO in production
import "hardhat/console.sol";
// import "@openzeppelin/contracts/";
// import "@openzeppelin/contracts/access/Ownable.sol";

interface SecretContract {
function newSecretUser(uint256 secret) external returns (uint256);
function linkPaymentRef(uint256 secret, string calldata ref) external returns (uint256);
function pay(string calldata ref, uint256 amount) external returns (uint256);
function payWithReceipt(string calldata ref, uint256 amount, uint256 userPubkey) external returns (uint256);
function withdraw(string calldata secret, address withdrawalAddress) external returns (uint256);
function retrievePubkey() external returns (uint256);
}

/**
* @author
*/
contract NunyaBusiness {

enum FunctionCallType {
OTHER, NEW_USER, NEW_REF, PAY, WITHDRAW, ERROR
}

struct Receipt {
uint256 paymentRef;
uint256 amount;
bytes32 sig;
}

address payable gateway;
SecretContract secretContract;
uint256 secretContractPubkey;
mapping (uint256 => FunctionCallType) expectedResult;

event ReceiptEmitted(Receipt);
event RequestSuccess(uint256 requestId);
event SecretNetworkError(uint256 requestId, string message);
event HackingAttemptError(uint256 requestId);

constructor(address payable _gateway) payable {
gateway = _gateway;
secretContract = SecretContract(_gateway);
fundGateway(msg.value);

secretContract.retrievePubkey();
// Lock secretContractPubkey to Owner. After it is set it cannot be reset.
secretContractPubkey = uint256(uint160(msg.sender));
}

modifier onlyGateway {
require (gateway!=address(0), "No gateway set");
require (msg.sender==gateway, "Only gateway can call callbacks. Use the user function instead");
_;
}

function setSecretContractPubkeyCallback (uint256 _requestId, uint256 _key) public onlyGateway {
// require (secretContractPubkey==0, "Key already set");
// Make sure it's our secret contract setting the key, not some interloper
// (will fail one time in 2^96 ;)
require (secretContractPubkey < 2**160, "Only the contract constructor can trigger this function");
secretContractPubkey=_key;
}

// Function wrapped in secret network payload encryption
function newSecretUser(uint256 _secret) public payable returns (uint256){
fundGateway(msg.value);
uint256 requestId = secretContract.newSecretUser(_secret);
expectedResult[requestId]==FunctionCallType.NEW_USER;
return(requestId);
}

function newSecretUserCallback(uint256 _requestId, bool _success) public onlyGateway {
require (expectedResult[_requestId]==FunctionCallType.NEW_USER);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - duplicate user?");
emit RequestSuccess(_requestId);
}

// Function wrapped in secret network payload encryption
function linkPaymentRef(uint256 _secret, string calldata _ref) public payable returns (uint256){
fundGateway(msg.value);
uint256 requestId = secretContract.linkPaymentRef(_secret, _ref);
expectedResult[requestId]=FunctionCallType.NEW_REF;
return(requestId);
}

function linkPaymentRefCallback(uint256 _requestId, bool _success) public onlyGateway{
require (expectedResult[_requestId]==FunctionCallType.NEW_REF);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - no user found?");
emit RequestSuccess(_requestId);
}

// TODO: use ref encrypted with (user pubkey+salt)
function pay(string calldata _ref, uint256 _value) public payable returns (uint256) {
// >= because we need gas for
require (_value >= msg.value, "Naughty!");
uint256 gasPaid = fundGateway();
uint256 requestId = secretContract.pay(_ref, msg.value-gasPaid);
expectedResult[requestId]=FunctionCallType.PAY;
return(requestId);
}

// TODO: use ref encrypted with (user pubkey+salt)
function pay(string calldata _ref, uint256 _value, uint256 _userPubkey) public payable returns (uint256) {
// >= because we need gas for
require (_value >= msg.value, "Naughty!");
uint256 gasPaid = fundGateway();
uint256 requestId = secretContract.payWithReceipt(_ref, msg.value-gasPaid, _userPubkey);
expectedResult[requestId]==FunctionCallType.PAY;
return(requestId);
}

// useful?
// function payEncrypted(string EncryptedRef) payable {
// secretContract.pay()
// }

function fundGateway(uint256 _gas) internal returns (uint256) {
gateway.transfer(_gas);
return _gas;
}

function fundGateway() internal returns (uint256) {
// TODO: calculate gas better than this!
uint256 gas=1;
gateway.transfer(gas);
return gas;
}

function payCallback(uint256 _requestId, bool _success) public payable onlyGateway {
require (expectedResult[_requestId]==FunctionCallType.PAY);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - wrong payment ref?");
emit RequestSuccess(_requestId);
}

function payCallback(uint256 _requestId, bool _success, Receipt calldata _receipt) public payable onlyGateway {
// TODO : use ecrecover to check receipt is signed by secret contract
require (expectedResult[_requestId]==FunctionCallType.PAY);
if (!_success)
emit SecretNetworkError(_requestId, "Error paying - wrong payment ref?");
if (uint256(_receipt.sig)!=0)
emit ReceiptEmitted(_receipt);
emit RequestSuccess(_requestId);
}

receive() external payable {

}

// Function wrapped in secret network payload encryption
function withdrawTo(string calldata _secret, uint256 _amount, address _withdrawalAddress) public payable returns (uint256) {
require((_amount > 0), "Account not found or empty.");
fundGateway(msg.value);
uint256 requestId = secretContract.withdraw(_secret, _withdrawalAddress);
// TODO: error check
expectedResult[requestId]=FunctionCallType.WITHDRAW;
return(requestId);
}

function withdrawToCallback(uint256 _requestId, bool _success, uint256 _amount, address payable _withdrawalAddress) onlyGateway public {
require (expectedResult[_requestId]==FunctionCallType.WITHDRAW);
if (!_success)
emit SecretNetworkError(_requestId, "Error withdrawing - out of funds?");
require(_amount > 0, "Account not found or empty.");
_withdrawalAddress.transfer(_amount);
emit RequestSuccess(_requestId);
}

function emitSecretNetworkError(uint256 _requestId, string memory _message) public onlyGateway {
emit SecretNetworkError(_requestId, _message);
}
}
3 changes: 2 additions & 1 deletion packages/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ const Home: NextPage = () => {
const [returnAmount, setReturnAmount] = useState("");
const { writeContractAsync } = useScaffoldWriteContract("NunyaBusiness");
// const encoder: TextEncoder = new global.TextEncoder();
// const decoder: TextDecoder = new global.TextDecoder();

useScaffoldWatchContractEvent({
contractName: "NunyaBusiness",
// TODO
// eventName: "reference-created",
eventName: "Request_success",
eventName: "RequestSuccess",
onLogs: logs => {
logs.forEach(() => {
// const { referenceBytes } = log.args;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const PaymentPage: NextPage<PageProps> = ({ params }: PageProps) => {
contractName: "NunyaBusiness",
// TODO
// eventName: "payment-receipt-received",
eventName: "Request_success",
eventName: "RequestSuccess",
onLogs: logs => {
logs.forEach(() => {
// const { receiptBytes } = log.args;
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/contracts/deployedContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const deployedContracts = {
type: "uint256",
},
],
name: "Request_success",
name: "RequestSuccess",
type: "event",
},
{
Expand Down
24 changes: 12 additions & 12 deletions packages/secret-contracts/nunya-contract/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,30 @@ unit-test:
# This is a local build with debug-prints activated. Debug prints only show up
# in the local development chain (see the `start-server` command below)
# and mainnet won't accept contracts built with the feature enabled.
#
# https://github.com/rust-bitcoin/rust-secp256k1/issues/283#issuecomment-1200858455
# RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown
.PHONY: build _build
build: _build compress-wasm
_build:
RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown
# RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown --features="debug-print"
cargo clean && AR=/opt/homebrew/opt/llvm/bin/llvm-ar CC=/opt/homebrew/opt/llvm/bin/clang RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown

# This is a build suitable for uploading to mainnet.
# Calls to `debug_print` get removed by the compiler.
#
# RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown
.PHONY: build-mainnet _build-mainnet
build-mainnet: _build-mainnet compress-wasm
_build-mainnet:
RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown
cargo clean && AR=/opt/homebrew/opt/llvm/bin/llvm-ar CC=/opt/homebrew/opt/llvm/bin/clang RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown

# like build-mainnet, but slower and more deterministic
.PHONY: build-mainnet-reproducible
build-mainnet-reproducible:
docker run --rm -v "$$(pwd)":/contract \
--mount type=volume,source="$$(basename "$$(pwd)")_cache",target=/contract/target \
--mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
enigmampc/secret-contract-optimizer:1.0.10
ghcr.io/scrtlabs/localsecret:v1.6.0-rc.3

.PHONY: compress-wasm
compress-wasm:
Expand All @@ -52,20 +56,16 @@ schema:
.PHONY: start-server
start-server: # CTRL+C to stop
docker run -it --rm \
-p 26657:26657 -p 26656:26656 -p 1317:1317 -p 5000:5000 \
-p 9091:9091 -p 26657:26657 -p 26656:26656 -p 1317:1317 -p 5000:5000 \
-v $$(pwd):/root/code \
--name localsecret ghcr.io/scrtlabs/localsecret:v1.6.0
--name secretdev ghcr.io/scrtlabs/localsecret:v1.6.0-rc.3

# This relies on running `start-server` in another console
# You can run other commands on the secretcli inside the dev image
# by using `docker exec localsecret secretcli`.
# by using `docker exec secretdev secretcli`.
.PHONY: store-contract-local
store-contract-local:
docker exec localsecret secretcli tx compute store -y --from a --gas 1000000 /root/code/contract.wasm.gz

.PHONY: integration-test
integration-test:
npx ts-node tests/integration.ts
docker exec secretdev secretcli tx compute store -y --from a --gas 1000000 /root/code/contract.wasm.gz

.PHONY: clean
clean:
Expand Down
1 change: 0 additions & 1 deletion packages/secret-contracts/nunya-contract/cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ secret-toolkit-serialization = { version = "0.10.0", features = ["base64"] }
tnls = { git = "https://github.com/SecretSaturn/TNLS", branch = "main", package = "secret_gateway", default-features = false }
# cw-storage-plus = { version = "0.14.0", default-features = false }


[[bin]]
name = "schema"
required-features = ["schema"]
Loading

0 comments on commit c988c58

Please sign in to comment.