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

[Task]: Withdrawal Bug fix #94

Open
wants to merge 1 commit into
base: casper-bridge
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
67 changes: 67 additions & 0 deletions bridge-backend/src/BridgeProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,73 @@ export class BridgeProcessor implements Injectable {
}
}

async createCasperSignedWithdraw(
item: UserBridgeWithdrawableBalanceItem
): Promise<[Boolean, UserBridgeWithdrawableBalanceItem?]> {
try {
let processed;
const sourceAddress = item.receiveAddress;
const targetAddress = item.receiveAddress;
const targetNetwork = item.sendNetwork;

const targetCurrency = item.receiveCurrency

const targetAmount = await this.helper.amountToMachine(
targetCurrency,
item.sendAmount
);
const salt = Web3.utils.keccak256(
`0x${item.id.toLocaleLowerCase()}`
);
console.log(salt, 'targetAmounttargetAmount')
const payBySig = await this.createSignedPayment(
item.receiveNetwork,
targetAddress,
targetCurrency,
targetAmount,
salt
);

processed = {
id: payBySig.hash, // same as signedWithdrawHash
timestamp: new Date().valueOf(),
receiveNetwork: item.receiveNetwork,
receiveCurrency: item.receiveCurrency,
receiveTransactionId: item.receiveTransactionId,
receiveAddress: sourceAddress,
receiveAmount: item.sendAmount,
payBySig,

sendNetwork: targetNetwork,
sendAddress: targetAddress,
sendTimestamp: new Date().valueOf(),
sendCurrency: item.receiveCurrency,
sendAmount: item.sendAmount,

used: "",
useTransactions: [],
} as UserBridgeWithdrawableBalanceItem;

await this.svc.withdrawSignedVerify(
item.receiveCurrency,
targetAddress,
targetAmount,
payBySig.hash,
"",
payBySig.signatures[0].signature,
this.processorAddress
);
await this.svc.newWithdrawItem(processed);
return [true, processed];
} catch (e) {
this.log.error(
`Error when processing transactions " ${e}`
);
return [false, undefined];
}
}


async createSignedPayment(
network: string,
address: string,
Expand Down
19 changes: 11 additions & 8 deletions bridge-backend/src/BridgeRequestProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,16 @@ export class BridgeRequestProcessor
this.registerProcessor('withdrawAndSwapGetTransaction',
(req, userId) => this.withdrawAndSwapGetTransaction(req, userId));

this.registerProcessor("logCsprTransaction", (req) => {
return this.bridgeProcessor.createCasperSignedWithdraw(req.data);
});

this.registerProcessor("logEvmAndNonEvmTransaction", (req) => {
return this.svc.logEvmAndNonEvmTransaction(req.data);
});

this.registerProcessor("getUserNonEvmWithdrawItems", (req) =>
this.getUserWithdrawItems(req, req.data.userAddress)
this.getUserWithdrawItems(req, req.data.userAddress, req.data.receiveAddress)
);

this.registerProcessor("processFromEvmSwapTransaction", (req) => {
Expand All @@ -136,11 +140,9 @@ export class BridgeRequestProcessor

this.registerProcessor("updateEvmAndNonEvmTransaction", async (req) => {
let item :any;
if (req.data && req.data.used !== "completed" && req.data.txType === "swap") {
console.log(req.data);
const signData = await this.bridgeProcessor.processEvmAndNonEvmTransaction(req.data.sendAddress, req.data.sendNetwork, req.data.sendCurrency, req.data.id, req.data.sendAmount);
console.log(signData, 'itemitem');
item = this.svc.updateEvmAndNonEvmTransaction({ ...req.data, sendNetwork: req.data.receiveNetwork, signData });
if (req.data && req.data.used !== "completed" && req.data.txType === "swap") {
const signData = await this.bridgeProcessor.processEvmAndNonEvmTransaction(req.data.sendAddress, req.data.receiveNetwork, req.data.sendCurrency, req.data.id, req.data.sendAmount);
item = this.svc.updateEvmAndNonEvmTransaction({ ...req.data, signData });
const res = await this.withdrawNonEvmSignedGetTransaction(req, req.data.user, {...req.data, ...signData})
return res;
}
Expand Down Expand Up @@ -220,13 +222,14 @@ export class BridgeRequestProcessor
return this.svc.getAvailableLiquidity(currency);
}

async getUserWithdrawItems(req: HttpRequestData, userId: string) {
async getUserWithdrawItems(req: HttpRequestData, userId: string, receiveAddress?: string) {
const { network } = req.data;
ValidationUtils.isTrue(!!userId, "user must be signed in");
ValidationUtils.isTrue(!!network, "'network' must be provided");
const items = await this.svc.getUserWithdrawItems(
network,
userId.toLowerCase()
userId.toLowerCase(),
receiveAddress
);
return { withdrawableBalanceItems: items };
}
Expand Down
2 changes: 1 addition & 1 deletion bridge-backend/src/BridgeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {ValidationUtils} from "ferrum-plumbing";
import axios from "axios";

const NAME = "FERRUM_TOKEN_BRIDGE_POOL";
const VERSION = "000.003";
const VERSION = "000.004";

export function domainSeparator(eth: Eth, netId: number, contractAddress: HexString) {
const hashedName = Web3.utils.keccak256(Web3.utils.utf8ToHex(NAME));
Expand Down
20 changes: 20 additions & 0 deletions bridge-backend/src/TokenBridgeContractClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,26 @@ export class TokenBridgeContractClinet implements Injectable {
`Withdraw `);
}

async withdrawCasperEvmSigned(w: UserBridgeWithdrawableBalanceItem,
from: string): Promise<CustomTransactionCallRequest>{
console.log(`About to withdrawSigned`, w);

const address = this.contractAddress[w.receiveNetwork];
const p = this.instance(w.receiveNetwork).methods.withdrawSigned(
//@ts-ignore
w.token, w.payee, w.amount, w.salt, w?.signature
)
const gas = await this.estimateGasOrDefault(p, from, undefined as any);
const nonce = await this.helper.web3(w.receiveNetwork).getTransactionCount(from, 'pending');
return Helper.callRequest(address,
w.sendCurrency,
from,
p.encodeABI(),
gas ? gas.toFixed() : undefined,
nonce,
`Withdraw `);
}

async approveIfRequired(userAddress: string, currency: string, amount: string):
Promise<CustomTransactionCallRequest[]> {
const [network, __] = Helper.parseCurrency(currency);
Expand Down
8 changes: 6 additions & 2 deletions bridge-backend/src/TokenBridgeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export class TokenBridgeService
// ),
// "Provided address is not the receiver of withdraw"
// );
return this.contract.withdrawEvmSigned(data, userAddress);
return this.contract.withdrawCasperEvmSigned(data, userAddress);
}

async addLiquidityGetTransaction(
Expand Down Expand Up @@ -403,14 +403,18 @@ export class TokenBridgeService

async getUserWithdrawItems(
network: string,
address: string
address: string,
receiveAddress: string
): Promise<UserBridgeWithdrawableBalanceItem[]> {
this.verifyInit();
const items = await this.balanceItem!.find({
$or: [
{
sendAddress: ChainUtils.canonicalAddress(network as any, address),
},
{
receiveAddress: receiveAddress,
},
{
receiveAddress: ChainUtils.canonicalAddress(network as any, address),
},
Expand Down
Loading