Skip to content

Commit

Permalink
Merge pull request #34 from willemolding/willem/fix-deposits-from-web
Browse files Browse the repository at this point in the history
Fix deposits from web
  • Loading branch information
willemolding committed May 16, 2024
2 parents d5866ef + cded6be commit 93703f1
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 28 deletions.
Binary file modified bridge-frontend/.yarn/install-state.gz
Binary file not shown.
2 changes: 1 addition & 1 deletion bridge-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"@web3-onboard/core": "^2.2.6",
"@web3-onboard/injected-wallets": "^2.0.5",
"@web3-onboard/react": "^2.1.5",
"bs58": "^5.0.0",
"@web3pack/base58-check": "^1.0.3",
"buffer": "^6.0.3",
"cacheable-request": "^10.2.7",
"ethers": "5.7.2",
Expand Down
12 changes: 7 additions & 5 deletions bridge-frontend/src/Transfers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ import {
Tab,
Card,
useColorMode,
Input,
} from "@chakra-ui/react";
import { Button, Box } from "@chakra-ui/react";
import { Stack } from "@chakra-ui/react";
import { Accordion } from "@chakra-ui/react";
import { Text } from "@chakra-ui/react";
import { Vouchers } from "./Vouchers";
import { EtherInput } from "./components/EtherInput";
import { ZCashTaddressInput } from "./components/ZCashTaddressInput";
import bs58 from "bs58";
import { decode as bs58decode } from '@web3pack/base58-check';

interface IInputPropos {
dappAddress: string;
Expand All @@ -43,15 +43,17 @@ export const Transfers: React.FC<IInputPropos> = (propos) => {
const { colorMode } = useColorMode();

const depositEtherToPortal = async (amount: string, destAddress: string) => {
console.log(`Depositing ${amount} to ${destAddress}`);
try {
if (rollups && provider) {
// parse the t-address into bytes we can send to the contract
let address_bytes = bs58.decode(destAddress);
let address_bytes = bs58decode(destAddress).subarray(2); // skip the first two bytes as they carry no information
const data = ethers.utils.arrayify(address_bytes);
const txOverrides = {
value: ethers.utils.parseEther(amount),
};
console.log("Ether to deposit: ", txOverrides);
console.log("Destination address: ", address_bytes);

// const tx = await ...
rollups.etherPortalContract.depositEther(
Expand Down Expand Up @@ -137,9 +139,9 @@ export const Transfers: React.FC<IInputPropos> = (propos) => {
value={etherAmount}
/>
<label>Destination Zcash Address</label>
<ZCashTaddressInput
<Input
value={destAddress}
onChange={(e: string) => setDestAddress(e)}
onChange={(e) => setDestAddress(e.target.value)}
/>
<Button
size="sm"
Expand Down
2 changes: 1 addition & 1 deletion bridge-frontend/src/components/ZCashTaddressInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState, useMemo } from "react";
import { Input } from "@chakra-ui/react";

export const T_ADDRESS_REGEX = /^t1[a-zA-Z0-9]{1,33}$/;
export const T_ADDRESS_REGEX = /^t1[a-zA-Z0-9]{0,33}$/;

/**
* Input for ETH amount with USD conversion.
Expand Down
19 changes: 19 additions & 0 deletions bridge-frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7769,6 +7769,24 @@ __metadata:
languageName: node
linkType: hard

"@web3pack/base-x@npm:^1.0.1":
version: 1.0.2
resolution: "@web3pack/base-x@npm:1.0.2"
checksum: 10c0/ec7dbe9baa4a522e12c7ae3c80d047f843f1c37806be00897bf4e7301120cc69ebe569f9cf9941394bca22977634780d6d389703683c2e61a328037d5975de6c
languageName: node
linkType: hard

"@web3pack/base58-check@npm:^1.0.3":
version: 1.0.3
resolution: "@web3pack/base58-check@npm:1.0.3"
dependencies:
"@web3pack/base-x": "npm:^1.0.1"
buffer: "npm:^6.0.3"
hash.js: "npm:^1.1.7"
checksum: 10c0/b0a25c6afcef9590aabe1d0a5fc4867188ca21947ecae249f3e2401610545c5d9f1748e3d027572b9472c316f78569ff23e681bce993f61ce3e477c572b0e801
languageName: node
linkType: hard

"@webassemblyjs/ast@npm:1.11.6, @webassemblyjs/ast@npm:^1.11.5":
version: 1.11.6
resolution: "@webassemblyjs/ast@npm:1.11.6"
Expand Down Expand Up @@ -9474,6 +9492,7 @@ __metadata:
"@web3-onboard/core": "npm:^2.2.6"
"@web3-onboard/injected-wallets": "npm:^2.0.5"
"@web3-onboard/react": "npm:^2.1.5"
"@web3pack/base58-check": "npm:^1.0.3"
assert: "npm:^2.0.0"
bs58: "npm:^5.0.0"
buffer: "npm:^6.0.3"
Expand Down
28 changes: 20 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ async fn main() -> Result<(), anyhow::Error> {
{
let grpc_addr = env::var("GRPC_SERVER_URL")?;
let state_read_service = Buffer::new(state_read_service.boxed(), 30);
let svc = CompactTxStreamerServer::new(CompactTxStreamerImpl::new(
let svc = CompactTxStreamerServer::new(CompactTxStreamerImpl::new(
state_read_service,
env::var("ETH_RPC_URL")?,
env::var("ETH_CHAIN_ID").map(|s| s.parse::<u64>().unwrap())?,
env::var("SIGNER_PK")?,
env::var("INPUTBOX_CONTRACT_ADDRESS")?,
env::var("DAPP_ADDRESS")?
env::var("DAPP_ADDRESS")?,
));
let addr = grpc_addr.parse()?;
let grpc_server = tonic::transport::Server::builder()
Expand Down Expand Up @@ -154,13 +154,14 @@ impl Service<RollAppRequest> for CarteZcashApp {
return async { Ok(tower_cartesi::Response::empty_accept()) }.boxed();
}

let czk_request = Request::try_from((metadata, payload)).unwrap();
let mut cartezcash_service = self.cartezcash.clone();

#[cfg(feature = "lightwalletd")]
let mut state_service = self.state_service.clone();
let dapp_address = self.dapp_address.clone();
async move {
let czk_request = Request::try_from((metadata, payload))?;

let response = cartezcash_service
.ready()
.await?
Expand All @@ -186,9 +187,14 @@ impl Service<RollAppRequest> for CarteZcashApp {
for (recipient, amount) in response.withdrawals {
tracing::info!("Withdrawal: to {:?} with amount: {:?}", recipient, amount);
if let Some(dapp_address) = dapp_address {
resp.add_voucher(dapp_address, &encode_withdraw_call(recipient, amount));
resp.add_voucher(
dapp_address,
&encode_withdraw_call(recipient, amount),
);
} else {
tracing::error!("Withdrawal made before dapp address set. Funds are lost.");
tracing::error!(
"Withdrawal made before dapp address set. Funds are lost."
);
}
}
Ok(resp)
Expand Down Expand Up @@ -242,11 +248,17 @@ where
Ok(())
}

fn encode_withdraw_call(recipient: ethereum_types::Address, amount: ethereum_types::U256) -> Vec<u8> {
fn encode_withdraw_call(
recipient: ethereum_types::Address,
amount: ethereum_types::U256,
) -> Vec<u8> {
let function = alloy_json_abi::Function::parse("withdrawEther(address,uint256)").unwrap();
let encoded_params = ethabi::encode(&[ethabi::Token::Address(recipient), ethabi::Token::Uint(amount)]);
let encoded_params = ethabi::encode(&[
ethabi::Token::Address(recipient),
ethabi::Token::Uint(amount),
]);
let mut encoded = Vec::new();
encoded.extend_from_slice(&function.selector().as_slice());
encoded.extend_from_slice(&encoded_params);
encoded
}
}
2 changes: 1 addition & 1 deletion src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl From<tiny_cash::service::Response> for Response {
.burns
.iter()
.map(|(amount, memo)| {
let addres_bytes = hex::decode(&memo.0[0..40]) // expect unicode hex no 0x prefix (inefficient). skip the version byte at the start
let addres_bytes = hex::decode(&memo.0[0..40]) // expect unicode hex no 0x prefix (inefficient). skip the version byte at the start
.expect("failed to decode memo");

(
Expand Down
2 changes: 1 addition & 1 deletion src/service/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl TryFrom<(tower_cartesi::AdvanceStateMetadata, Vec<u8>)> for Request {

let dest_t_address = Address::from_pub_key_hash(
tiny_cash::parameters::Network::Mainnet,
payload[52..].try_into().unwrap(),
payload[52..].try_into()?,
);
let amount = Amount::try_from(value.as_u64())?; // FIX: This is going to panic if too much eth is sent

Expand Down
30 changes: 19 additions & 11 deletions tower-cartesi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub enum Error<E> {
pub async fn listen_http<S>(service: &mut S, host_uri: &str) -> Result<(), Error<S::Error>>
where
S: Service<Request, Response = Response>,
S::Error: std::fmt::Debug,
{
let client = reqwest::Client::new();

Expand All @@ -47,17 +48,24 @@ where
let request = Request::try_from(rollup_request)?;

// let the dapp process the request
response = service.call(request).await.map_err(Error::ServiceError)?;

// handle the additional calls as required by the dApp outputs
for output in response.outputs.iter() {
tracing::info!("Sending output {:?}", output);
let resp = client
.post(format!("{}/{}", host_uri, output.url_path()))
.json(&output)
.send()
.await;
tracing::info!("Output response: {:?}", resp);
match service.call(request).await.map_err(Error::ServiceError) {
Ok(r) => {
response = r;
// handle the additional calls as required by the dApp outputs
for output in response.outputs.iter() {
tracing::info!("Sending output {:?}", output);
let resp = client
.post(format!("{}/{}", host_uri, output.url_path()))
.json(&output)
.send()
.await;
tracing::info!("Output response: {:?}", resp);
}
}
Err(e) => {
tracing::error!("{:?}", e);
response = Response::empty_reject();
}
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions tower-cartesi/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ impl Response {
}
}

pub fn empty_reject() -> Self {
Self {
status: Status::Reject,
outputs: Vec::new(),
}
}

pub fn add_voucher(&mut self, destination: ethereum_types::Address, payload: &[u8]) {
self.outputs.push(Output::Voucher {
destination,
Expand Down

0 comments on commit 93703f1

Please sign in to comment.