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

Experiment/payable callback #23

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ yarn-error.log*

# vercel
.vercel

# Foundry
/cache
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[submodule "lib/openzeppelin-contracts"]
path = lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
[submodule "lib/medusa-contracts"]
path = lib/medusa-contracts
url = https://github.com/medusa-network/medusa-contracts
104 changes: 104 additions & 0 deletions contracts/OnlyFiles.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity ^0.8.19;

import {
MedusaClient,
IEncryptionClient,
IEncryptionOracle,
Ciphertext,
ReencryptedCipher,
G1Point
} from "./MedusaClient.sol";
import {PullPayment} from "@openzeppelin/contracts/security/PullPayment.sol";

error ListingDoesNotExist();
error InsufficentFunds();

struct Listing {
address seller;
uint256 price;
string uri;
}

contract OnlyFiles is MedusaClient, PullPayment {
/// @notice A mapping from cipherId to listing
mapping(uint256 => Listing) public listings;

event ListingDecryption(
uint256 indexed requestId, ReencryptedCipher reencryptedCipher
);
event NewListing(
address indexed seller,
uint256 indexed cipherId,
Ciphertext ciphertext,
string name,
string description,
uint256 price,
string uri
);
event NewSale(
address indexed buyer,
address indexed seller,
uint256 requestId,
uint256 cipherId
);

constructor(IEncryptionOracle _oracle) MedusaClient(_oracle) {}

/// @notice Create a new listing
/// @dev Submits a ciphertext to the oracle, stores a listing, and emits an event
/// @return cipherId The id of the ciphertext associated with the new listing
function createListing(
Ciphertext calldata cipher,
string calldata name,
string calldata description,
uint256 price,
string calldata uri
) external returns (uint256) {
uint256 cipherId = oracle.submitCiphertext(cipher, msg.sender);
listings[cipherId] = Listing(msg.sender, price, uri);
emit NewListing(
msg.sender, cipherId, cipher, name, description, price, uri
);
return cipherId;
}

/// @notice Pay for a listing
/// @dev Buyer pays the price for the listing, which can be withdrawn by the seller later; emits an event
/// @return requestId The id of the reencryption request associated with the purchase
function buyListing(uint256 cipherId, G1Point calldata buyerPublicKey)
external
payable
returns (uint256)
{
Listing memory listing = listings[cipherId];
if (listing.seller == address(0)) {
revert ListingDoesNotExist();
}
if (msg.value < listing.price) {
revert InsufficentFunds();
}

_asyncTransfer(listing.seller, listing.price);
uint256 requestId = oracle.requestReencryption{
value: msg.value - listing.price
}(cipherId, buyerPublicKey);

emit NewSale(msg.sender, listing.seller, requestId, cipherId);
return requestId;
}

function processOracleResult(
uint256 requestId,
ReencryptedCipher memory cipher
) internal override {
emit ListingDecryption(requestId, cipher);
}

/// @notice Convenience function to get the public key of the oracle
/// @dev This is the public key that sellers should use to encrypt their listing ciphertext
/// @dev Note: This feels like a nice abstraction, but it's not strictly necessary
function publicKey() external view returns (G1Point memory) {
return oracle.distributedKey();
}
}
25 changes: 25 additions & 0 deletions foundry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[profile.default]
src = 'contracts'
out = 'out'
libs = ['lib']
fs_permissions = [{ access = "read", path = "./broadcast"}]
remappings = ["@medusa=lib/medusa-contracts/src","@openzeppelin/contracts=lib/openzeppelin-contracts/contracts"]

# See more config options https://github.com/gakonst/foundry/tree/master/configr
optimizer = true
optimizer_runs = 200
solc-version = "0.8.19"
verbosity = 4

[fmt]
line_length = 80

[rpc_endpoints]
local = "http://localhost:8545"
arbitrum = "https://arb1.arbitrum.io/rpc"
arbitrum-goerli = "${ARBITRUM_GOERLI_RPC_URL}"
hyperspace = "https://api.hyperspace.node.glif.io/rpc/v1"

[etherscan]
arbitrum = { key = "${ETHERSCAN_KEY}" }
arbitrum-goerli = { key = "${ETHERSCAN_KEY}" }
1 change: 1 addition & 0 deletions lib/medusa-contracts
Submodule medusa-contracts added at 4f2b5c
1 change: 1 addition & 0 deletions lib/openzeppelin-contracts
Submodule openzeppelin-contracts added at 8d633c
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
},
"dependencies": {
"@heroicons/react": "^1.0.6",
"@medusa-network/medusa-sdk": "0.0.2",
"@medusa-network/medusa-sdk": "0.1.0-rc2",
"@tailwindcss/forms": "^0.5.3",
"autoprefixer": "^10.4.7",
"connectkit": "^1.2.2",
"ethers": "^5.7.1",
"ethers": "^5",
"js-base64": "^3.7.3",
"next": "12.3.1",
"next-plausible": "^3.7.2",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions remappings.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@openzeppelin/contracts=lib/openzeppelin-contracts/contracts
@medusa=lib/medusa-contracts/src
37 changes: 29 additions & 8 deletions src/components/EventsFetcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ import {
default as useGlobalStore,
} from '@/stores/globalStore'
import { BigNumber, ethers } from 'ethers'
import { HGamalEVMCipher as Ciphertext } from '@medusa-network/medusa-sdk'
import {
HGamalEVMCipher as Ciphertext,
HGamalEVMReencryptedCipher as ReencryptedCipher,
} from '@medusa-network/medusa-sdk'

const EventsFetcher: FC = () => {
const provider = useProvider()
Expand Down Expand Up @@ -43,12 +46,21 @@ const EventsFetcher: FC = () => {
listener(
seller: string,
cipherId: BigNumber,
ciphertext: Ciphertext,
name: string,
description: string,
price: BigNumber,
uri: string,
) {
addListing({ seller, cipherId, name, description, price, uri })
addListing({
seller,
cipherId,
ciphertext,
name,
description,
price,
uri,
})
},
})

Expand All @@ -72,8 +84,8 @@ const EventsFetcher: FC = () => {
address: chainConfig?.appContractAddress,
abi: CONTRACT_ABI,
eventName: 'ListingDecryption',
listener(requestId: BigNumber, ciphertext: Ciphertext) {
addDecryption({ requestId, ciphertext })
listener(requestId: BigNumber, reencryptedCipher: ReencryptedCipher) {
addDecryption({ requestId, reencryptedCipher })
},
})

Expand Down Expand Up @@ -110,8 +122,17 @@ const EventsFetcher: FC = () => {
)
const listings = newListings.map((filterTopic: ethers.Event) => {
const result = iface.parseLog(filterTopic)
const { seller, cipherId, name, description, price, uri } = result.args
return { seller, cipherId, name, description, price, uri } as Listing
const { seller, cipherId, ciphertext, name, description, price, uri } =
result.args
return {
seller,
cipherId,
ciphertext,
name,
description,
price,
uri,
} as Listing
})
updateListings(listings)

Expand All @@ -131,8 +152,8 @@ const EventsFetcher: FC = () => {
const decryptions = listingDecryptions.map(
(filterTopic: ethers.Event) => {
const result = iface.parseLog(filterTopic)
const { requestId, ciphertext } = result.args
return { requestId, ciphertext } as Decryption
const { requestId, reencryptedCipher } = result.args
return { requestId, reencryptedCipher } as Decryption
},
)
updateDecryptions(decryptions)
Expand Down
32 changes: 26 additions & 6 deletions src/components/Listing.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { CHAIN_CONFIG, CONTRACT_ABI } from '@/lib/consts'
import useMedusa from '@/hooks/useMedusa'
import { FC, useEffect, useState } from 'react'
import { Listing as ListingProps } from '@/stores/globalStore'
import useMedusa from '@/hooks/useMedusa'
import toast from 'react-hot-toast'
import { BigNumber } from 'ethers'
import { formatEther } from 'ethers/lib/utils'
import { FC } from 'react'
import toast from 'react-hot-toast'
import {
useAccount,
useContractWrite,
Expand All @@ -13,6 +12,7 @@ import {
useWaitForTransaction,
} from 'wagmi'
import Signin from '@/components/Signin'
import { CHAIN_CONFIG, CONTRACT_ABI } from '@/lib/consts'

const Listing: FC<ListingProps & { purchased: boolean }> = ({
cipherId,
Expand All @@ -25,20 +25,37 @@ const Listing: FC<ListingProps & { purchased: boolean }> = ({
const { isConnected } = useAccount()
const { medusa } = useMedusa()
const { chain } = useNetwork()
const [callbackGas, setCallbackGas] = useState(BigNumber.from(0))
useEffect(() => {
const getCallbackGas = async () => {
if (medusa) {
try {
const gas = await medusa.estimateCallbackGas(appContractAddress)
console.log(gas)

setCallbackGas(gas)
} catch (e) {
console.log(e)
}
}
}
getCallbackGas()
}, [medusa])

let buyerPublicKey = null
if (medusa?.keypair) {
const { x, y } = medusa.keypair.pubkey.toEvm()
buyerPublicKey = { x, y }
}

const appContractAddress = CHAIN_CONFIG[chain?.id]?.appContractAddress
const { config } = usePrepareContractWrite({
address: CHAIN_CONFIG[chain?.id]?.appContractAddress,
address: appContractAddress,
abi: CONTRACT_ABI,
functionName: 'buyListing',
args: [cipherId, buyerPublicKey],
enabled: Boolean(buyerPublicKey) && Boolean(chain),
overrides: { value: price },
overrides: { value: price.add(callbackGas) },
chainId: chain?.id,
})

Expand Down Expand Up @@ -76,6 +93,9 @@ const Listing: FC<ListingProps & { purchased: boolean }> = ({

const unlockSecret = async () => {
toast.loading('Unlocking secret...')

const gas = await medusa.estimateCallbackGas(appContractAddress)
console.log('Gas to send for callback', gas)
buyListing?.()
}

Expand Down
9 changes: 6 additions & 3 deletions src/components/ListingForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ const ListingForm: FC = () => {
const [cid, setCid] = useState('')
const [submitting, setSubmitting] = useState(false)

const chainConfig = CHAIN_CONFIG[chain?.id]

const {
config,
error: prepareError,
isError: isPrepareError,
isSuccess: readyToSendTransaction,
} = usePrepareContractWrite({
address: CHAIN_CONFIG[chain?.id]?.appContractAddress,
address: chainConfig?.appContractAddress,
abi: CONTRACT_ABI,
functionName: 'createListing',
args: [
Expand All @@ -58,12 +60,13 @@ const ListingForm: FC = () => {
} = useContractWrite(config)

useEffect(() => {
if (readyToSendTransaction) {
if (readyToSendTransaction && chainConfig) {
toast.loading('Submitting secret to Medusa...')

createListing?.()
setCid('')
}
}, [readyToSendTransaction])
}, [readyToSendTransaction, chainConfig])

const { isLoading, isSuccess } = useWaitForTransaction({
hash: data?.hash,
Expand Down
4 changes: 3 additions & 1 deletion src/components/Unlocked.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ const Unlocked: FC<Sale> = ({ buyer, seller, requestId, cipherId }) => {
const decryptContent = async () => {
if (!decryption || !signer || !medusa?.keypair) return

const { ciphertext } = decryption
const { reencryptedCipher } = decryption
const { ciphertext } = listing

console.log('Downloading encrypted content from ipfs')
const ipfsDownload = ipfsGatewayLink(listing.uri)
Expand All @@ -35,6 +36,7 @@ const Unlocked: FC<Sale> = ({ buyer, seller, requestId, cipherId }) => {
try {
const decryptedBytes = await medusa.decrypt(
ciphertext,
reencryptedCipher,
encryptedContents,
)
const msg = new TextDecoder().decode(decryptedBytes)
Expand Down
Loading