Skip to content

Commit

Permalink
Fixes to deposit, withdraw, balances, tokens, templates (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
fadeev authored Mar 28, 2024
1 parent f264c64 commit 0c2a31c
Show file tree
Hide file tree
Showing 14 changed files with 155 additions and 109 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@
"@openzeppelin/contracts": "^4.9.2",
"@uniswap/v2-periphery": "^1.1.0-beta.0",
"@zetachain/faucet-cli": "^4.0.1",
"@zetachain/networks": "4.0.0-rc1",
"@zetachain/protocol-contracts": "5.0.0-rc7",
"@zetachain/networks": "6.0.0",
"@zetachain/protocol-contracts": "7.0.0-rc1",
"axios": "^1.4.0",
"bech32": "^2.0.0",
"bip39": "^3.1.0",
Expand All @@ -105,4 +105,4 @@
"tiny-secp256k1": "^2.2.3",
"ws": "^8.13.0"
}
}
}
21 changes: 13 additions & 8 deletions packages/client/src/deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import { prepareParams } from "./prepareData";
* @param options.message - If a message is specified, ZetaChain will deposit
* tokens into the `recipient` contract and call with with the message as an argument.
* @param options.recipient - Recipient address for the deposit. If not provided,
* the deposit is made to the signer's address. If the message is provided, the
* recipient is assumed to be a contract address.
* the deposit is made to the signer's address.
*
* @returns A promise that resolves with the transaction details upon success.
*/
Expand All @@ -32,9 +31,9 @@ export const deposit = async function (
{
chain,
amount,
recipient,
erc20,
message,
recipient,
}: {
amount: string;
chain: string;
Expand All @@ -54,6 +53,14 @@ export const deposit = async function (
} else {
throw new Error("No wallet or signer found.");
}
if (message && !recipient) {
throw new Error("Please, provide a valid contract address as recipient.");
}
const to = recipient || this.signer.address;
const abiCoder = ethers.utils.defaultAbiCoder;
const data = message
? abiCoder.encode(message[0], message[1])
: ethers.utils.hexlify([]);
if (erc20) {
const custody = getAddress(
"erc20Custody",
Expand Down Expand Up @@ -81,10 +88,6 @@ export const deposit = async function (
}
const approveTx = await contract.approve(custody, value);
await approveTx.wait();
const to = recipient || signer.address;
const data = message
? prepareParams(message[0], message[1])
: ethers.utils.hexlify([]);
return await custodyContract.deposit(to, erc20, value, data);
} else {
const tss = getAddress("tss", chain as ParamChainName);
Expand All @@ -99,7 +102,9 @@ export const deposit = async function (
to: tss,
value: ethers.utils.parseUnits(amount, 18),
};
if (recipient) tx.data = `${recipient}${message ?? ""}`;
tx.data = recipient
? `${recipient}${data.slice(2) ?? ""}`
: ethers.utils.hexlify([]);
return await signer.sendTransaction(tx);
}
};
53 changes: 35 additions & 18 deletions packages/client/src/getBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,23 @@ export const getBalances = async function (
symbol: "ZETA",
});

tokens = tokens.map((token: any) => {
const ticker = token.symbol.split("-")[0];
const { chain_name } = supportedChains.find(
(c: any) => c.chain_id === token.chain_id.toString()
);
return {
...token,
chain_name,
id: `${token.chain_id.toString().toLowerCase()}__${token.symbol
.toLowerCase()
.split(" ")
.join("_")}`,
ticker,
};
});
tokens = tokens
.map((token: any) => {
const ticker = token.symbol.split("-")[0];
const chain_name = supportedChains.find(
(c: any) => c.chain_id === token.chain_id.toString()
)?.chain_name;
return {
...token,
chain_name,
id: `${token.chain_id.toString().toLowerCase()}__${token.symbol
.toLowerCase()
.split(" ")
.join("_")}`,
ticker,
};
})
.filter((token: any) => token.chain_name);

const balances = await Promise.all(
tokens.map(async (token: any) => {
Expand All @@ -112,13 +114,23 @@ export const getBalances = async function (
const isERC = token.coin_type === "ERC20";
const isZRC = token.coin_type === "ZRC20";
if (isGas && !isBitcoin) {
const rpc = await this.getEndpoint("evm", token.chain_name);
let rpc;
try {
rpc = await this.getEndpoint("evm", token.chain_name);
} catch (e) {
return token;
}
const provider = new ethers.providers.StaticJsonRpcProvider(rpc);
return provider.getBalance(evmAddress).then((balance) => {
return { ...token, balance: formatUnits(balance, token.decimals) };
});
} else if (isGas && isBitcoin && btcAddress) {
const API = this.getEndpoint("esplora", "btc_testnet");
let API;
try {
API = this.getEndpoint("esplora", token.chain_name);
} catch (e) {
return { ...token, balance: undefined };
}
return fetch(`${API}/address/${btcAddress}`).then(async (response) => {
const r = await response.json();
const { funded_txo_sum, spent_txo_sum } = r.chain_stats;
Expand All @@ -129,7 +141,12 @@ export const getBalances = async function (
return { ...token, balance };
});
} else if (isERC) {
const rpc = await this.getEndpoint("evm", token.chain_name);
let rpc;
try {
rpc = await this.getEndpoint("evm", token.chain_name);
} catch (e) {
return token;
}
const provider = new ethers.providers.StaticJsonRpcProvider(rpc);
const contract = new ethers.Contract(
token.contract,
Expand Down
9 changes: 8 additions & 1 deletion packages/client/src/sendZeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ export const sendZeta = async function (

const destinationChainId = this.getChains()[destination]?.chain_id;
const destinationAddress = recipient ? recipient : signer.address;

console.log({
destinationAddress,
destinationChainId,
destinationGasLimit: gasLimit,
message: ethers.utils.toUtf8Bytes(""),
zetaParams: ethers.utils.toUtf8Bytes(""),
zetaValueAndGas: value,
});
return await connectorContract.send({
destinationAddress,
destinationChainId,
Expand Down
9 changes: 0 additions & 9 deletions packages/client/src/trackCCTX.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,6 @@ const fetchCCTXData = async function (
const receiver_chainId = cctx?.outbound_tx_params[0]?.receiver_chainId;
const outbound_tx_hash = cctx?.outbound_tx_params[0]?.outbound_tx_hash;
let confirmed_on_destination = false;
if (outbound_tx_hash) {
const chainName = findByChainId(networks, parseInt(receiver_chainId));
if (chainName) {
const rpc = this.getEndpoint("evm", chainName as any);
const provider = new ethers.providers.JsonRpcProvider(rpc);
const confirmed = await provider.getTransaction(outbound_tx_hash);
confirmed_on_destination = confirmed !== null;
}
}
const tx = {
confirmed_on_destination,
outbound_tx_hash,
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const withdraw = async function (
} else {
throw new Error("No wallet or signer found.");
}

const targetContract = new ethers.Contract(zrc20, ZRC20.abi, signer);
const targetDecimals = await targetContract.decimals();

Expand Down
56 changes: 18 additions & 38 deletions packages/tasks/src/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,42 +30,6 @@ const balancesError = `
npx hardhat balances --address <wallet_address>
`;

const summarizeTokens = (tokens: any[]) => {
let table = {} as any;
tokens.forEach((token) => {
if (token && token.chain_name) {
if (!table[token.chain_name]) {
table[token.chain_name] = {};
}
const balance = parseFloat(token.balance).toFixed(2);
if (parseFloat(token.balance) > 0) {
if (token.coin_type === "Gas") {
table[token.chain_name].gas = balance;
} else if (token.symbol === "ZETA") {
table[token.chain_name].zeta = balance;
} else if (token.coin_type === "ERC20") {
table[token.chain_name].erc20 =
(table[token.chain_name].erc20
? table[token.chain_name].erc20 + " "
: "") +
balance +
" " +
token.symbol;
} else if (token.coin_type === "ZRC20") {
table[token.chain_name].zrc20 =
(table[token.chain_name].zrc20
? table[token.chain_name].zrc20 + " "
: "") +
balance +
" " +
token.symbol;
}
}
}
});
return table;
};

const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const client = new ZetaChainClient({
network: args.mainnet ? "mainnet" : "testnet",
Expand All @@ -89,7 +53,7 @@ const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
console.error(walletError + balancesError);
return process.exit(1);
}
const balances = (await client.getBalances({
let balances = (await client.getBalances({
btcAddress,
evmAddress,
})) as any;
Expand All @@ -101,7 +65,23 @@ const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
console.log(`
EVM: ${evmAddress} ${btcAddress ? `\nBitcoin: ${btcAddress}` : ""}
`);
console.table(summarizeTokens(balances));
balances = balances.sort((a: any, b: any) => {
if (a?.chain_name === undefined && b?.chain_name === undefined) return 0;
if (a?.chain_name === undefined) return 1;
if (b?.chain_name === undefined) return -1;

return a.chain_name.localeCompare(b.chain_name);
});

balances = balances.map((balance: any) => ({
/* eslint-disable */
Chain: balance.chain_name,
Token: balance.symbol,
Type: balance.coin_type,
Amount: `${parseFloat(balance.balance).toFixed(6)}`,
/* eslint-enable */
}));
console.table(balances);
}
};

Expand Down
10 changes: 5 additions & 5 deletions packages/tasks/src/deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
msg[0].every((item: string) => typeof item === "string") &&
msg[1].every((item: string) => typeof item === "string")
) {
message = args.message;
message = JSON.parse(args.message);
} else {
throw new Error('must be an array like [["string"], ["hello"]]');
}
Expand All @@ -33,14 +33,14 @@ const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
}
}

const recipient = args.recipient || signer.address;
// const recipient = args.recipient || signer.address;

const chain = hre.network.name;
if (chain === "zeta_testnet" || chain === "zeta_mainnet") {
throw new Error("Cannot from ZetaChain to ZetaChain.");
}

const data = { amount, chain, erc20, message, recipient };
const data = { amount, chain, erc20, message, recipient: args.recipient };

let symbol;
if (erc20) {
Expand All @@ -62,9 +62,9 @@ const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
Networks: ${chain} → zeta_testnet
Amount sent: ${amount} ${symbol || ""}
Sender: ${signer.address}
Recipient: ${recipient}`);
Recipient: ${args.recipient || signer.address}`);
if (message) {
console.log(`Message: ${message}`);
console.log(`Message: ${args.message}`);
}
await confirm(
{
Expand Down
1 change: 1 addition & 0 deletions packages/tasks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export { poolsTask } from "./pools";
export { sendBTCTask } from "./sendBTC";
export { sendZETATask } from "./sendZETA";
// export { verifyTask } from "./verify";
export { tokensTask } from "./tokens";
export { withdrawTask } from "./withdraw";
30 changes: 16 additions & 14 deletions packages/tasks/src/sendZETA.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,28 @@ const main = async (args: any, hre: any) => {
throw new Error(`Cannot fetch fees for chain ID ${chainID}`);
}
fee = chainFee.totalFee;
if (parseFloat(args.amount) < parseFloat(fee))
if (parseFloat(args.amount) < parseFloat(fee) && !args.ignoreChecks) {
throw new Error(
`Amount must be greater than ${fee} ZETA to cover the cross-chain fees`
);
}
}

const { amount, destination } = args;
const recipient = args.recipient || signer.address;
const chain = hre.network.name;

const data: any = {
amount,
chain,
destination,
recipient,
};

if (args.gasLimit) data.gasLimit = args.gasLimit;

if (args.json) {
const tx = await client.sendZeta({
amount,
chain,
destination,
recipient,
});
const tx = await client.sendZeta(data);
console.log(JSON.stringify(tx, null, 2));
} else {
console.log(`
Expand All @@ -56,12 +61,7 @@ To address: ${recipient}
},
{ clearPromptOnDone: true }
);
const tx = await client.sendZeta({
amount,
chain,
destination,
recipient,
});
const tx = await client.sendZeta(data);
console.log(`Transaction successfully broadcasted!
Hash: ${tx.hash}`);
}
Expand All @@ -75,4 +75,6 @@ export const sendZETATask = task(
.addParam("amount", "Amount of ZETA to send")
.addParam("destination", "Destination chain")
.addOptionalParam("recipient", "Recipient address")
.addFlag("json", "Output JSON");
.addFlag("json", "Output JSON")
.addOptionalParam("gasLimit", "Gas limit")
.addFlag("ignoreChecks", "Ignore fee check");
Loading

0 comments on commit 0c2a31c

Please sign in to comment.