Unverified Commit 7cc0d1c3 authored by vipwzw's avatar vipwzw Committed by GitHub

Merge pull request #1115 from YingQm/bridgevmxgo_bsc_1201

Bridgevmxgo bsc 1201
parents a94f7b0c 07e80c51
FROM ubuntu:16.04
RUN apt-get -qq update \
&& apt-get -qq install -y --no-install-recommends ca-certificates curl
WORKDIR /root
COPY ebrelayer ebrelayer
COPY ebcli_A ebcli_A
......
......@@ -4,7 +4,7 @@ services:
ganachetest:
entrypoint: ["node", "/app/ganache-core.docker.cli.js", "-a", "20", "-b", "2", "--debug", "-m", "coast bar giraffe art venue decide symbol law visual crater vital fold", "-e", "1000"]
image: trufflesuite/ganache-cli:latest
#ports:
# ports:
# - "8545:8545"
ebrelayera:
......
......@@ -782,6 +782,10 @@ function StartDockerRelayerDeploy() {
# 部署合约 设置 bridgeRegistry 地址
InitAndOfflineDeploy
# 设置 ethereum symbol
${Boss4xCLI} ethereum offline set_symbol -s "ETH" -c "${ethBridgeBank}" -d "${ethDeployAddr}"
ethereum_offline_sign_send "set_symbol.txt"
# 设置离线多签数据
Chain33Cli=${MainCli}
initMultisignChain33Addr
......@@ -809,7 +813,7 @@ function StartDockerRelayerDeploy() {
# 设置 token 地址
# InitTokenAddr
offline_create_bridge_token_eth_BTY
offline_create_bridge_token_chain33_ETH
offline_create_bridge_token_chain33_ETH "ETH"
offline_deploy_erc20_eth_BYC
offline_create_bridge_token_chain33_BYC
offline_deploy_erc20_chain33_YCC
......
......@@ -164,6 +164,23 @@ function offline_create_bridge_token_chain33_USDT() {
${CLIA} chain33 token set -t "${chain33USDTBridgeTokenAddr}" -s USDT
}
function offline_create_bridge_token_chain33_BUSD() {
# 在chain33上创建bridgeToken BUSD
echo -e "${GRE}======= 在 chain33 上创建 bridgeToken BUSD ======${NOC}"
# shellcheck disable=SC2154
${Boss4xCLI} chain33 offline create_bridge_token -c "${chain33BridgeBank}" -s BUSD -k "${chain33DeployKey}" --chainID "${chain33ID}"
chain33_offline_send "create_bridge_token.txt"
chain33BUSDBridgeTokenAddr=$(${Chain33Cli} evm query -a "${chain33BridgeBank}" -c "${chain33DeployAddr}" -b "getToken2address(BUSD)")
echo "BUSD Bridge Token Addr = ${chain33BUSDBridgeTokenAddr}"
cp BridgeToken.abi "${chain33BUSDBridgeTokenAddr}.abi"
result=$(${Chain33Cli} evm query -a "${chain33BUSDBridgeTokenAddr}" -c "${chain33BUSDBridgeTokenAddr}" -b "symbol()")
is_equal "${result}" "BUSD"
${CLIA} chain33 token set -t "${chain33BUSDBridgeTokenAddr}" -s BUSD
}
function offline_deploy_erc20_chain33_YCC() {
# chain33 token create YCC
echo -e "${GRE}======= 在 chain33 上创建 ERC20 YCC ======${NOC}"
......@@ -216,18 +233,19 @@ function offline_create_bridge_token_eth_BTY() {
function offline_create_bridge_token_chain33_ETH() {
# 在 chain33 上创建 bridgeToken ETH
echo -e "${GRE}======= 在 chain33 上创建 bridgeToken ETH ======${NOC}"
${Boss4xCLI} chain33 offline create_bridge_token -c "${chain33BridgeBank}" -s ETH -k "${chain33DeployKey}" --chainID "${chain33ID}" -n "create_bridge_token:ETH"
echo -e "${GRE}======= 在 chain33 上创建 bridgeToken $1 ======${NOC}"
local symbolName="$1"
${Boss4xCLI} chain33 offline create_bridge_token -c "${chain33BridgeBank}" -s "${symbolName}" -k "${chain33DeployKey}" --chainID "${chain33ID}" -n "create_bridge_token:${symbolName}"
chain33_offline_send "create_bridge_token.txt"
chain33EthBridgeTokenAddr=$(${Chain33Cli} evm query -a "${chain33BridgeBank}" -c "${chain33DeployAddr}" -b "getToken2address(ETH)")
echo "ETH Token Addr= ${chain33EthBridgeTokenAddr}"
chain33EthBridgeTokenAddr=$(${Chain33Cli} evm query -a "${chain33BridgeBank}" -c "${chain33DeployAddr}" -b "getToken2address(${symbolName})")
echo "${symbolName} Token Addr= ${chain33EthBridgeTokenAddr}"
cp BridgeToken.abi "${chain33EthBridgeTokenAddr}.abi"
result=$(${Chain33Cli} evm query -a "${chain33EthBridgeTokenAddr}" -c "${chain33EthBridgeTokenAddr}" -b "symbol()")
is_equal "${result}" "ETH"
is_equal "${result}" "${symbolName}"
${CLIA} chain33 token set -t "${chain33EthBridgeTokenAddr}" -s ETH
${CLIA} chain33 token set -t "${chain33EthBridgeTokenAddr}" -s "${symbolName}"
}
function offline_create_bridge_token_eth_YCC() {
......@@ -281,7 +299,7 @@ function offline_transfer_multisign_Eth_test() {
# transfer
# shellcheck disable=SC2154
# ${CLIA} ethereum multisign transfer -a 3 -r "${ethBridgeBank}" -o "${ethValidatorAddrKeyB}" -k "${ethMultisignKeyA},${ethMultisignKeyB},${ethMultisignKeyC},${ethMultisignKeyD}"
${Boss4xCLI} ethereum offline multisign_transfer_prepare -a 3 -r "${ethBridgeBank}" -c "${multisignEthAddr}" -d "${ethTestAddr1}"
${Boss4xCLI} ethereum offline multisign_transfer_prepare -a 0.001 -r "${ethBridgeBank}" -c "${multisignEthAddr}" -d "${ethTestAddr1}"
# shellcheck disable=SC2154
${Boss4xCLI} ethereum offline sign_multisign_tx -k "${ethMultisignKeyA},${ethMultisignKeyB},${ethMultisignKeyC},${ethMultisignKeyD}"
${Boss4xCLI} ethereum offline create_multisign_tx
......@@ -290,23 +308,23 @@ function offline_transfer_multisign_Eth_test() {
sleep 10
result=$(${CLIA} ethereum balance -o "${ethBridgeBank}")
cli_ret "${result}" "balance" ".balance" "16"
# cli_ret "${result}" "balance" ".balance" "16"
result=$(${CLIA} ethereum balance -o "${multisignEthAddr}")
cli_ret "${result}" "balance" ".balance" "20"
# cli_ret "${result}" "balance" ".balance" "20"
# transfer
# shellcheck disable=SC2154
# ${CLIA} ethereum multisign transfer -a 5 -r "${ethMultisignA}" -o "${ethValidatorAddrKeyB}" -k "${ethMultisignKeyA},${ethMultisignKeyB},${ethMultisignKeyC},${ethMultisignKeyD}"
${Boss4xCLI} ethereum offline multisign_transfer_prepare -a 5 -r "${ethMultisignA}" -c "${multisignEthAddr}" -d "${ethTestAddr1}"
${Boss4xCLI} ethereum offline multisign_transfer_prepare -a 0.001 -r "${ethMultisignA}" -c "${multisignEthAddr}" -d "${ethTestAddr1}"
${Boss4xCLI} ethereum offline sign_multisign_tx -k "${ethMultisignKeyA},${ethMultisignKeyB},${ethMultisignKeyC},${ethMultisignKeyD}"
${Boss4xCLI} ethereum offline create_multisign_tx
ethereum_offline_sign_send create_multisign_tx.txt "${ethTestAddrKey1}"
sleep 10
result=$(${CLIA} ethereum balance -o "${ethMultisignA}")
cli_ret "${result}" "balance" ".balance" "1005"
# cli_ret "${result}" "balance" ".balance" "1005"
result=$(${CLIA} ethereum balance -o "${multisignEthAddr}")
cli_ret "${result}" "balance" ".balance" "15"
# cli_ret "${result}" "balance" ".balance" "15"
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
......
......@@ -593,3 +593,65 @@ function kill_all_ebrelayer() {
cp ./ebrelayer relayer_${name}/ebrelayer
done
}
function get_config() {
local fileName=$1
local param=$2
value=$(sed -E '/^#.*|^ *$/d' "${fileName}" | awk -F "${param}=" "/${param}=/{print \$2}" | tail -n1)
echo "${value}"
}
function init_read_address() {
local fileName=$1
# shellcheck disable=SC2034
{
ethDeployAddr=$(get_config "${fileName}" "ethDeployAddr")
ethDeployKey=$(get_config "${fileName}" "ethDeployKey")
ethValidatorAddra=$(get_config "${fileName}" "ethValidatorAddra")
ethValidatorAddrb=$(get_config "${fileName}" "ethValidatorAddrb")
ethValidatorAddrc=$(get_config "${fileName}" "ethValidatorAddrc")
ethValidatorAddrd=$(get_config "${fileName}" "ethValidatorAddrd")
ethValidatorAddrKeya=$(get_config "${fileName}" "ethValidatorAddrKeya")
ethValidatorAddrKeyb=$(get_config "${fileName}" "ethValidatorAddrKeyb")
ethValidatorAddrKeyc=$(get_config "${fileName}" "ethValidatorAddrKeyc")
ethValidatorAddrKeyd=$(get_config "${fileName}" "ethValidatorAddrKeyd")
ethTestAddr1=$(get_config "${fileName}" "ethTestAddr1")
ethTestAddrKey1=$(get_config "${fileName}" "ethTestAddrKey1")
ethTestAddr2=$(get_config "${fileName}" "ethTestAddr2")
ethTestAddrKey2=$(get_config "${fileName}" "ethTestAddrKey2")
ethReceiverAddr1=$(get_config "${fileName}" "ethReceiverAddr1")
ethMultisignA=$(get_config "${fileName}" "ethMultisignA")
ethMultisignB=$(get_config "${fileName}" "ethMultisignB")
ethMultisignC=$(get_config "${fileName}" "ethMultisignC")
ethMultisignD=$(get_config "${fileName}" "ethMultisignD")
ethMultisignKeyA=$(get_config "${fileName}" "ethMultisignKeyA")
ethMultisignKeyB=$(get_config "${fileName}" "ethMultisignKeyB")
ethMultisignKeyC=$(get_config "${fileName}" "ethMultisignKeyC")
ethMultisignKeyD=$(get_config "${fileName}" "ethMultisignKeyD")
chain33DeployAddr=$(get_config "${fileName}" "chain33DeployAddr")
chain33DeployKey=$(get_config "${fileName}" "chain33DeployKey")
chain33Validatora=$(get_config "${fileName}" "chain33Validatora")
chain33Validatorb=$(get_config "${fileName}" "chain33Validatorb")
chain33Validatorc=$(get_config "${fileName}" "chain33Validatorc")
chain33Validatord=$(get_config "${fileName}" "chain33Validatord")
chain33ValidatorKeya=$(get_config "${fileName}" "chain33ValidatorKeya")
chain33ValidatorKeyb=$(get_config "${fileName}" "chain33ValidatorKeyb")
chain33ValidatorKeyc=$(get_config "${fileName}" "chain33ValidatorKeyc")
chain33ValidatorKeyd=$(get_config "${fileName}" "chain33ValidatorKeyd")
chain33TestAddr1=$(get_config "${fileName}" "chain33TestAddr1")
chain33TestAddrKey1=$(get_config "${fileName}" "chain33TestAddrKey1")
chain33TestAddr2=$(get_config "${fileName}" "chain33TestAddr2")
chain33TestAddrKey2=$(get_config "${fileName}" "chain33TestAddrKey2")
chain33ReceiverAddr=$(get_config "${fileName}" "ethDeployAddr")
chain33ReceiverAddrKey=$(get_config "${fileName}" "ethDeployAddr")
chain33MultisignA=$(get_config "${fileName}" "chain33MultisignA")
chain33MultisignB=$(get_config "${fileName}" "chain33MultisignB")
chain33MultisignC=$(get_config "${fileName}" "chain33MultisignC")
chain33MultisignD=$(get_config "${fileName}" "chain33MultisignD")
chain33MultisignKeyA=$(get_config "${fileName}" "chain33MultisignKeyA")
chain33MultisignKeyB=$(get_config "${fileName}" "chain33MultisignKeyB")
chain33MultisignKeyC=$(get_config "${fileName}" "chain33MultisignKeyC")
chain33MultisignKeyD=$(get_config "${fileName}" "chain33MultisignKeyD")
}
}
......@@ -334,6 +334,17 @@ function validators_config() {
# shellcheck disable=SC2154
sed -i ''"${line}"' a validatorsAddr=['\""${chain33Validatora}"\"', '\""${chain33Validatorb}"\"', '\""${chain33Validatorc}"\"', '\""${chain33Validatord}"\"']' "./relayer.toml"
fi
line=$(delete_line_show "./relayer.toml" 'operatorAddr="0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a"')
if [ "${line}" ]; then
sed -i ''"${line}"' a operatorAddr='\""${ethDeployAddr}"\"'' "./relayer.toml"
fi
line=$(delete_line_show "./relayer.toml" 'validatorsAddr=\["0x92C8b16aFD6d423652559C6E266cBE1c29Bfd84f')
if [ "${line}" ]; then
# shellcheck disable=SC2154
sed -i ''"${line}"' a validatorsAddr=['\""${ethValidatorAddra}"\"', '\""${ethValidatorAddrb}"\"', '\""${ethValidatorAddrc}"\"', '\""${ethValidatorAddrd}"\"']' "./relayer.toml"
fi
}
function StartRelayerAndDeploy() {
......@@ -436,6 +447,52 @@ function InitChain33Validator() {
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
function coins_cross_transfer() {
local key="${1}"
local addr="${2}"
local amount="${3}"
local para_amount="${4}"
local evm_amount="${5}"
# 先把 bty 转入到 paracross 合约中
# shellcheck disable=SC2154
hash=$(${MainCli} send coins send_exec -e paracross -a "${amount}" -k "${key}")
check_tx "${MainCli}" "${hash}"
# 主链中的 bty 夸链到 平行链中
# shellcheck disable=SC2154
hash=$(${Para8801Cli} send para cross_transfer -a "${para_amount}" -e coins -s bty -t "${addr}" -k "${key}")
check_tx "${Para8801Cli}" "${hash}"
# shellcheck disable=SC2154
check_tx "${Para8901Cli}" "${hash}"
result=$(${Para8901Cli} asset balance -a "${addr}" --asset_exec paracross --asset_symbol coins.bty | jq -r .balance)
is_equal "${result}" "${para_amount}.0000"
# 把平行链中的 bty 转入 平行链中的 evm 合约
hash=$(${Para8901Cli} send para transfer_exec -a "${evm_amount}" -e user.p.para.evm -s coins.bty -k "${key}")
check_tx "${Para8901Cli}" "${hash}"
result=$(${Para8901Cli} asset balance -a "${addr}" --asset_exec paracross --asset_symbol coins.bty -e user.p.para.evm | jq -r .balance)
is_equal "${result}" "${evm_amount}.0000"
}
function initPara() {
# para add
hash=$(${Para8901Cli} send coins transfer -a 10000 -n test -t "${chain33ReceiverAddr}" -k CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944)
check_tx "${Para8901Cli}" "${hash}"
Chain33Cli=${Para8901Cli}
InitChain33Validator
coins_cross_transfer "${chain33DeployKey}" "${chain33DeployAddr}" 1000 800 500
coins_cross_transfer "${chain33TestAddrKey1}" "${chain33TestAddr1}" 1000 800 500
coins_cross_transfer "${chain33TestAddrKey2}" "${chain33TestAddr2}" 1000 800 500
# 平行链共识节点增加测试币
${MainCli} send coins transfer -a 1000 -n test -t "1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4" -k "${chain33ReceiverAddrKey}"
${MainCli} send coins transfer -a 1000 -n test -t "1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR" -k "${chain33ReceiverAddrKey}"
${MainCli} send coins transfer -a 1000 -n test -t "1NLHPEcbTWWxxU3dGUZBhayjrCHD3psX7k" -k "${chain33ReceiverAddrKey}"
${MainCli} send coins transfer -a 1000 -n test -t "1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs" -k "${chain33ReceiverAddrKey}"
}
function StartChain33() {
kill_ebrelayer chain33
sleep 2
......
#!/usr/bin/env bash
# shellcheck disable=SC2128
# shellcheck source=/dev/null
set -x
set +e
# 主要在平行链上测试
source "./offlinePublic.sh"
# shellcheck disable=SC2034
{
# ETH 部署合约者的私钥 用于部署合约时签名使用
ethDeployAddr="0x8AFDADFC88a1087c9A1D6c0F5Dd04634b87F303a"
ethDeployKey="0x8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230"
# chain33 部署合约者的私钥 用于部署合约时签名使用
chain33DeployAddr="1JxhYLYsrscjTaQfaMoVUrnSdrejP7XRQD"
chain33DeployKey="0x9ef82623a5e9aac58d3a6b06392af66ec77289522b28896aed66abaaede66903"
# validatorsAddr=["0x92C8b16aFD6d423652559C6E266cBE1c29Bfd84f", "0x0df9a824699bc5878232c9e612fe1a5346a5a368", "0xcb074cb21cdddf3ce9c3c0a7ac4497d633c9d9f1", "0xd9dab021e74ecf475788ed7b61356056b2095830"]# shellcheck disable=SC2034
# eth 验证者私钥
ethValidatorAddra="0x92C8b16aFD6d423652559C6E266cBE1c29Bfd84f"
ethValidatorAddrb="0x0df9a824699bc5878232c9e612fe1a5346a5a368"
ethValidatorAddrc="0xcb074cb21cdddf3ce9c3c0a7ac4497d633c9d9f1"
ethValidatorAddrd="0xd9dab021e74ecf475788ed7b61356056b2095830"
ethValidatorAddrKeya="3fa21584ae2e4fd74db9b58e2386f5481607dfa4d7ba0617aaa7858e5025dc1e"
ethValidatorAddrKeyb="a5f3063552f4483cfc20ac4f40f45b798791379862219de9e915c64722c1d400"
ethValidatorAddrKeyc="bbf5e65539e9af0eb0cfac30bad475111054b09c11d668fc0731d54ea777471e"
ethValidatorAddrKeyd="c9fa31d7984edf81b8ef3b40c761f1847f6fcd5711ab2462da97dc458f1f896b"
# 新增地址 chain33 需要导入地址 转入 10 bty当收费费
chain33Validatora="1N6HstkyLFS8QCeVfdvYxx1xoryXoJtvvZ"
chain33Validatorb="155ooMPBTF8QQsGAknkK7ei5D78rwDEFe6"
chain33Validatorc="13zBdQwuyDh7cKN79oT2odkxYuDbgQiXFv"
chain33Validatord="113ZzVamKfAtGt9dq45fX1mNsEoDiN95HG"
chain33ValidatorKeya="0x027ca96466c71c7e7c5d73b7e1f43cb889b3bd65ebd2413eefd31c6709c262ae"
chain33ValidatorKeyb="0x9d539bc5fd084eb7fe86ad631dba9aa086dba38418725c38d9751459f567da66"
chain33ValidatorKeyc="0x0a6671f101e30a2cc2d79d77436b62cdf2664ed33eb631a9c9e3f3dd348a23be"
chain33ValidatorKeyd="0x3818b257b05ee75b6e43ee0e3cfc2d8502342cf67caed533e3756966690b62a5"
ethTestAddr1=0xbc333839E37bc7fAAD0137aBaE2275030555101f
ethTestAddrKey1=0x0c61f5a879d70807686e43eccc1f52987a15230ae0472902834af4d1933674f2
ethTestAddr2=0x495953A743ef169EC5D4aC7b5F786BF2Bd56aFd5
ethTestAddrKey2=0x2809477ede1261da21270096776ba7dc68b89c9df5f029965eaa5fe7f0b80697
ethReceiverAddr1="0xa4ea64a583f6e51c3799335b28a8f0529570a635"
#ethReceiverAddrKey1="355b876d7cbcb930d5dfab767f66336ce327e082cbaa1877210c1bae89b1df71"
chain33TestAddr1="1Cj1rqUenPmkeD6A8MGEzkBKQFN2H9yL3x"
chain33TestAddrKey1="0x7269a7a87d476310da37a9ca1ddc9333c9d7a0dfe1f2998b84758843a895433b"
chain33TestAddr2="1BCGLhdcdthNutQowV2YShuuN9fJRRGLxu"
chain33TestAddrKey2="0xb74acfd4eebbbd07bcae212baa7f094235ab8dc04f2f1d828681477b98b24008"
chain33ReceiverAddr="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv"
chain33ReceiverAddrKey="4257d8692ef7fe13c68b65d6a52f03933db2fa5ce8faf210b5b8b80c721ced01"
chain33BridgeBank=""
ethBridgeBank=""
chain33BtyERC20TokenAddr="1111111111111111111114oLvT2"
chain33EthBridgeTokenAddr=""
ethereumBtyBridgeTokenAddr=""
chain33BycBridgeTokenAddr=""
ethereumBycERC20TokenAddr=""
BridgeRegistryOnChain33=""
chain33YccERC20TokenAddr=""
BridgeRegistryOnEth=""
ethereumYccBridgeTokenAddr=""
chain33ZbcERC20TokenAddr=""
ethereumZbcBridgeTokenAddr=""
multisignChain33Addr=""
multisignEthAddr=""
Chain33Cli=""
maturityDegree=10
chain33ID=0
}
# shellcheck disable=SC2120
function offline_set_offline_token_Bty() {
echo -e "${GRE}=========== $FUNCNAME begin ===========${NOC}"
echo -e "${GRE}===== chain33 端 configLockedTokenOfflineSave BTY ======${NOC}"
# echo '2:#配置自动转离线钱包(bty, 100, 50%)'
local threshold=10000000000
local percents=50
if [[ $# -eq 2 ]]; then
threshold=$1
percents=$2
fi
# shellcheck disable=SC2086
${Boss4xCLI} chain33 offline set_offline_token -c "${chain33BridgeBank}" -s BTY -m ${threshold} -p ${percents} -k "${chain33DeployKey}" --chainID "${chain33ID}"
chain33_offline_send "chain33_set_offline_token.txt"
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
# shellcheck disable=SC2120
function offline_set_offline_token_Chain33Ycc() {
echo -e "${GRE}=========== $FUNCNAME begin ===========${NOC}"
echo -e "${GRE}===== chain33 端 configLockedTokenOfflineSave ERC20 YCC ======${NOC}"
# echo '2:#配置自动转离线钱包(YCC, 100, 60%)'
local threshold=10000000000
local percents=60
if [[ $# -eq 2 ]]; then
threshold=$1
percents=$2
fi
# shellcheck disable=SC2086
${Boss4xCLI} chain33 offline set_offline_token -c "${chain33BridgeBank}" -t "${chain33YccERC20TokenAddr}" -s YCC -m ${threshold} -p ${percents} -k "${chain33DeployKey}" --chainID "${chain33ID}"
chain33_offline_send "chain33_set_offline_token.txt"
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
# shellcheck disable=SC2120
function offline_set_offline_token_Eth() {
echo -e "${GRE}=========== $FUNCNAME begin ===========${NOC}"
# echo '2:#配置自动转离线钱包(eth, 20, 50%)'
local threshold=20
local percents=50
if [[ $# -eq 2 ]]; then
threshold=$1
percents=$2
fi
# shellcheck disable=SC2086
${Boss4xCLI} ethereum offline set_offline_token -s ETH -m ${threshold} -p ${percents} -c "${ethBridgeBank}" -d "${ethDeployAddr}"
ethereum_offline_sign_send "set_offline_token.txt"
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
# shellcheck disable=SC2120
function offline_set_offline_token_EthYcc() {
echo -e "${GRE}=========== $FUNCNAME begin ===========${NOC}"
local threshold=100
local percents=40
if [[ $# -eq 2 ]]; then
threshold=$1
percents=$2
fi
# shellcheck disable=SC2086
${Boss4xCLI} ethereum offline set_offline_token -s BYC -m ${threshold} -p ${percents} -t "${ethereumBycERC20TokenAddr}" -c "${ethBridgeBank}" -d "${ethDeployAddr}"
ethereum_offline_sign_send "set_offline_token.txt"
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
function MainTest() {
set +e
chain33ID=0
chain33BridgeBank=15Myyvq97WinTWto8zcEdm838zXmvJKfnX
ethBridgeBank=0xC65B02a22B714b55D708518E2426a22ffB79113d
# ethereumBtyBridgeTokenAddr=0x9c3d40a44a2f61ef8d46fa8c7a731c08fb16ccef
# chain33EthBridgeTokenAddr=1JVFbJhFUWUNH41PxbV7NqwUd3F9BJ3nqV
ethereumBycERC20TokenAddr=0x20a32A5680EBf55740B0C98B54cDE8e6FD5a4FB0
# ethereumYccBridgeTokenAddr=0x05f3f31c7d53bcb71a6487dff3115d86370698bd
# chain33BycBridgeTokenAddr=1BdREGqsjbcKkvRheXWYKRq37vJHMs22Uy
chain33YccERC20TokenAddr=17yu1yULdGFddUz26PEeaHpJtkFGEpzYrA
# chain33ZbcERC20TokenAddr=1AqRwUa4T3q9DuCyUwn5ucHgtUhbUP2yfu
# ethereumZbcBridgeTokenAddr=0x89bb32184e466a9c8ea50c31174b575c2bcd64c2
dockerNamePrefix="build"
docker_chain33_ip=$(get_docker_addr "${dockerNamePrefix}_chain33_1")
# MainCli="./chain33-cli --rpc_laddr http://${docker_chain33_ip}:8801"
# Para8801Cli="./chain33-cli --rpc_laddr http://${docker_chain33_ip}:8901 --paraName user.p.para."
Para8901Cli="./chain33-cli --rpc_laddr http://${docker_chain33_ip}:8901 --paraName user.p.para."
# shellcheck disable=SC2034
{
CLIA="docker exec ${dockerNamePrefix}_ebrelayera_1 /root/ebcli_A"
CLIB="docker exec ${dockerNamePrefix}_ebrelayerb_1 /root/ebcli_A"
CLIC="docker exec ${dockerNamePrefix}_ebrelayerc_1 /root/ebcli_A"
CLID="docker exec ${dockerNamePrefix}_ebrelayerd_1 /root/ebcli_A"
docker_ganachetest_ip=$(get_docker_addr "${dockerNamePrefix}_ganachetest_1")
Boss4xCLI="docker exec ${dockerNamePrefix}_ebrelayera_1 /root/boss4x --rpc_laddr http://${docker_chain33_ip}:8901 --rpc_laddr_ethereum http://${docker_ganachetest_ip}:8545 --paraName user.p.para."
echo "${Boss4xCLI}"
}
# shellcheck disable=SC2034
Chain33Cli=${Para8901Cli}
# 离线多签地址转入阈值设大
offline_set_offline_token_Bty 100000000000000 10
offline_set_offline_token_Chain33Ycc 100000000000000 10
offline_set_offline_token_Eth 100000000000000 10
offline_set_offline_token_EthYcc 100000000000000 10
echo -e "${GRE}=========== $FUNCNAME end ===========${NOC}"
}
MainTest
......@@ -2,9 +2,7 @@
# shellcheck disable=SC2128
# shellcheck source=/dev/null
#source "./dockerRelayerTest.sh"
source "./dockerRelayerTestEvm.sh"
#source "./dockerRelayerTestInfinite.sh"
source "./paracrosstestcase.sh"
function bridgevmxgo() {
......
......@@ -73,10 +73,10 @@ func CreateERC20(cmd *cobra.Command, _ []string) {
Addr: fromAddr,
}
createPara := fmt.Sprintf("%s,%s,%s,%s", symbol, symbol, fmt.Sprintf("%d", amountInt64), owner)
createPara := fmt.Sprintf("%s,%s,%s,%s,8", symbol, symbol, fmt.Sprintf("%d", amountInt64), owner)
content, txHash, err := utils.CreateContractAndSign(getTxInfo(cmd), erc20.ERC20Bin, erc20.ERC20ABI, createPara, "ERC20:"+symbol)
if nil != err {
fmt.Println("CreateContractAndSign erc20 fail")
fmt.Println("CreateContractAndSign erc20 fail", err.Error())
return
}
......
......@@ -28,6 +28,7 @@ func main() {
rootCmd.PersistentFlags().String("paraName", "", "para chain name,Eg:user.p.fzm.")
rootCmd.PersistentFlags().String("expire", "120m", "transaction expire time (optional)")
rootCmd.PersistentFlags().Int32("chainID", 0, "chain id, default to 0")
rootCmd.PersistentFlags().Int64("chainEthId", 56, "ethereum chain id, default to 0")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
......
package offline
import (
"fmt"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/33cn/plugin/plugin/dapp/cross2eth/contracts/contracts4eth/generated"
"github.com/spf13/cobra"
)
func ConfigplatformTokenSymbolCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "set_symbol",
Short: "save config symbol",
Run: ConfigplatformTokenSymbol,
}
addConfigplatformTokenSymbolFlags(cmd)
return cmd
}
func addConfigplatformTokenSymbolFlags(cmd *cobra.Command) {
cmd.Flags().StringP("symbol", "s", "ETH", "symbol")
_ = cmd.MarkFlagRequired("symbol")
cmd.Flags().StringP("deployAddr", "d", "", "deploy contract addr")
_ = cmd.MarkFlagRequired("deployAddr")
cmd.Flags().StringP("contract", "c", "", "bridgebank contract address")
_ = cmd.MarkFlagRequired("contract")
}
func ConfigplatformTokenSymbol(cmd *cobra.Command, _ []string) {
url, _ := cmd.Flags().GetString("rpc_laddr_ethereum")
symbol, _ := cmd.Flags().GetString("symbol")
deployAddr, _ := cmd.Flags().GetString("deployAddr")
contract, _ := cmd.Flags().GetString("contract")
bridgeAbi, err := abi.JSON(strings.NewReader(generated.BridgeBankABI))
if err != nil {
fmt.Println("JSON NewReader Err:", err)
return
}
abiData, err := bridgeAbi.Pack("configplatformTokenSymbol", symbol)
if err != nil {
panic(err)
}
CreateTxInfoAndWrite(abiData, deployAddr, contract, "set_symbol", url)
}
......@@ -81,7 +81,7 @@ func DeployERC20(cmd *cobra.Command, _ []string) {
}
bin := common.FromHex(erc20.ERC20Bin)
Erc20OwnerAddr := common.HexToAddress(owner)
packdata, err := parsed.Pack("", symbol, symbol, bnAmount, Erc20OwnerAddr)
packdata, err := parsed.Pack("", symbol, symbol, bnAmount, Erc20OwnerAddr, uint8(8))
if err != nil {
fmt.Println("Pack error", err.Error())
return
......
......@@ -185,6 +185,8 @@ func NewTxWrite(infos []*DeployInfo, deployerAddr common.Address, url, fileName
gasLimit = 100 * 10000
}
ntx := types.NewTx(&types.LegacyTx{
//ntx := types.NewTx(&types.AccessListTx{
// ChainID: big.NewInt(chainId),
Nonce: info.Nonce,
Gas: gasLimit,
GasPrice: price,
......
......@@ -3,8 +3,18 @@
#### 基础步骤
* 在线创建交易 `./boss4x ethereum offline create ...` 需要在线查询 nonce 等信息
* 离线签名交易 `./boss4x ethereum offline sign -f xxx.txt -k 8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230`
* 离线签名交易 `./boss4x ethereum offline sign -f xxx.txt -k 8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230 --chainEthId xxx`
* 在线发送签名后文件 `./boss4x ethereum offline send -f deploysigntxs.txt` 默认签名后的文件名称都是 deploysigntxs.txt
```
Global Flags:
--chainEthId int ethereum chain id, default to 0 (default 56 is bsc)
--chainID int32 chain id, default to 0
--expire string transaction expire time (optional) (default "120m")
--paraName string para chain name,Eg:user.p.fzm.
--rpc_laddr string http url (default "https://localhost:8801")
--rpc_laddr_ethereum string ethereum http url (default "http://localhost:7545")
```
***
#### 离线部署 ethereum 跨链合约
......@@ -20,7 +30,7 @@
交易7: 部署合约: MulSign
命令:
./boss4x ethereum offline create -p 25,25,25,25 -o 0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a -v 0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a,0x0df9a824699bc5878232c9e612fe1a5346a5a368,0xcb074cb21cdddf3ce9c3c0a7ac4497d633c9d9f1,0xd9dab021e74ecf475788ed7b61356056b2095830
./boss4x ethereum offline create -p 25,25,25,25 -o 0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a -v 0x8afdadfc88a1087c9a1d6c0f5dd04634b87f303a,0x0df9a824699bc5878232c9e612fe1a5346a5a368,0xcb074cb21cdddf3ce9c3c0a7ac4497d633c9d9f1,0xd9dab021e74ecf475788ed7b61356056b2095830 --paraName xxx --rpc_laddr xxx --rpc_laddr_ethereum xxx
参数说明:
-p, --initPowers string 验证者权重, as: '25,25,25,25'
......@@ -37,11 +47,12 @@ tx is written to file: deploytxs.txt
* 离线签名交易
```
./boss4x ethereum offline sign -k 8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230
./boss4x ethereum offline sign -k 8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230 --chainEthId xxx
参数说明:
-f, --file string 需要签名的文件, 默认:deploytxs.txt (default "deploytxs.txt")
-k, --key string 部署者的私钥
--chainEthId chainId, 如果是Bsc, chainId为56, 如果是ethereum, chainId为1, 查询链接:https://chainlist.org/
```
* 发送签名后文件
......@@ -49,6 +60,32 @@ tx is written to file: deploytxs.txt
./boss4x ethereum offline send -f deploysigntxs.txt
```
***
#### 设置 symbol
* 在线创建交易
```
命令:
./boss4x ethereum offline set_symbol -s "BNB" -c "${ethBridgeBank}" -d "${ethDeployAddr}"
参数说明:
-c, --contract string bridgebank合约地址
-d, --deployAddr string 部署合约的地址
-s, --symbol string 要设置的 symbol, 默认为 ETH
输出
tx is written to file: set_symbol.txt
```
* 离线签名交易
```
./boss4x ethereum offline sign -f set_symbol.txt -k 8656d2bc732a8a816a461ba5e2d8aac7c7f85c26a813df30d5327210465eb230
```
* 发送签名后文件
```
./boss4x ethereum offline send -f deploysigntxs.txt
```
#### 离线部署 ERC20 跨链合约
* 在线创建交易
```
......@@ -77,6 +114,7 @@ tx is written to file: deployErc20YCC.txt
```
***
#### create_add_lock_list
* 在线创建交易
```
......@@ -94,6 +132,7 @@ tx is written to file: create_add_lock_list.txt
```
***
#### 创建 bridge token
* 在线创建交易
```
......@@ -110,6 +149,7 @@ tx is written to file: create_bridge_token.txt
```
***
#### 设置离线多签地址信息
* 在线创建交易
```
......@@ -126,6 +166,7 @@ tx is written to file: multisign_setup.txt
```
***
#### 设置离线多签地址
* 在线创建交易
```
......@@ -142,6 +183,7 @@ tx is written to file: set_offline_addr.txt
```
***
#### 离线多签设置
* 在线创建交易
```
......@@ -161,6 +203,7 @@ tx is written to file: set_offline_token.txt
```
***
#### 离线多签转帐
* 转帐预备交易--在线操作
```
......
......@@ -4,25 +4,17 @@ import (
"context"
"encoding/json"
"fmt"
//"github.com/33cn/plugin/plugin/dapp/cross2eth/contracts/contracts4eth/generated"
//erc20 "github.com/33cn/plugin/plugin/dapp/cross2eth/contracts/erc20/generated"
//"github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/utils"
tml "github.com/BurntSushi/toml"
"github.com/ethereum/go-ethereum"
//"github.com/ethereum/go-ethereum/accounts/abi"
"io/ioutil"
"math/big"
"os"
tml "github.com/BurntSushi/toml"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/spf13/cobra"
//"strings"
//"time"
)
type DeployContractRet struct {
......@@ -52,6 +44,7 @@ func DeployOfflineContractsCmd() *cobra.Command {
CreateMultisignTransferTxCmd(), // 创建多签转帐交易
SignCmd(), // 签名交易 sign deploy contract tx
SendTxsCmd(), // 发送交易 send all kinds of tx
ConfigplatformTokenSymbolCmd(),
)
return cmd
......
......@@ -58,7 +58,7 @@ func sendTxs(cmd *cobra.Command, _ []string) {
ret := &DeployContractRet{ContractAddr: deployInfo.ContractorAddr.String(), TxHash: tx.Hash().String(), ContractName: deployInfo.Name}
respData = append(respData, ret)
if !checkTxStatus(client, tx.Hash().String(), deployInfo.Name) {
fmt.Println("FATAL ERROR! DEPLOY CONTRACTOR TERMINATION……:-(")
//fmt.Println("FATAL ERROR! DEPLOY CONTRACTOR TERMINATION……:-(")
break
}
}
......@@ -81,7 +81,7 @@ func checkTxStatus(client *ethclient.Client, txhash, txName string) bool {
case <-checkticket.C:
receipt, err := client.TransactionReceipt(context.Background(), common.HexToHash(txhash))
if err == ethereum.NotFound {
fmt.Println("\n No receipt received yet for "+txName, " tx and continue to wait")
//fmt.Println("\n No receipt received yet for "+txName, " tx and continue to wait")
continue
} else if err != nil {
panic("failed due to" + err.Error())
......
......@@ -29,6 +29,7 @@ func addSignFlag(cmd *cobra.Command) {
func signTx(cmd *cobra.Command, _ []string) {
privatekey, _ := cmd.Flags().GetString("key")
txFilePath, _ := cmd.Flags().GetString("file")
chainEthId, _ := cmd.Flags().GetInt64("chainEthId")
deployPrivateKey, err := crypto.ToECDSA(common.FromHex(privatekey))
if err != nil {
panic(err)
......@@ -47,7 +48,7 @@ func signTx(cmd *cobra.Command, _ []string) {
if err != nil {
panic(err)
}
signedTx, txHash, err := eoff.SignTx(deployPrivateKey, &tx)
signedTx, txHash, err := eoff.SignEIP155Tx(deployPrivateKey, &tx, chainEthId)
if err != nil {
panic(err)
}
......
......@@ -665,6 +665,10 @@ function StartDockerRelayerDeploy() {
# 部署合约 设置 bridgeRegistry 地址
InitAndOfflineDeploy
# 设置 ethereum symbol
${Boss4xCLI} ethereum offline set_symbol -s "ETH" -c "${ethBridgeBank}" -d "${ethDeployAddr}"
ethereum_offline_sign_send "set_symbol.txt"
# 设置离线多签数据
Chain33Cli=${MainCli}
initMultisignChain33Addr
......
##
##编译solidity,并产生bin文件,abi文件,和相应的go文件
SRC_BEP := bep20
SRC_ERC20 := erc20
SRC_CONTRACT0 := contracts4chain33
SRC_CONTRACT1 := contracts4eth
SRC_MULTISIGN := gnosis/safe-contracts/contracts
......@@ -9,6 +10,8 @@ SRC_MULTISIGN := gnosis/safe-contracts/contracts
GO_OUT0 := ${SRC_CONTRACT0}/generated
GO_OUT1 := ${SRC_CONTRACT1}/generated
GO_OUT_MULTISIGN := gnosis/generated
GO_OUT_BEP20 := bep20/generated
GO_OUT_ERC20 := erc20/generated
PACKAGE := generated
proj := "build"
......@@ -21,10 +24,17 @@ build: depends
@abigen --sol $(SRC_CONTRACT0)/BridgeBank/BridgeBank.sol --pkg $(PACKAGE) --out $(GO_OUT0)/BridgeBank.go
@abigen --sol $(SRC_CONTRACT1)/BridgeRegistry.sol --pkg $(PACKAGE) --out $(GO_OUT1)/BridgeRegistry.go
@abigen --sol $(SRC_CONTRACT1)/BridgeBank/BridgeBank.sol --pkg $(PACKAGE) --out $(GO_OUT1)/BridgeBank.go
@abigen --sol $(SRC_BEP)/BEP20.sol --pkg $(PACKAGE) --out $(GO_OUT_BEP20)/bep20.go
multisign:
@abigen --sol $(SRC_MULTISIGN)/GnosisSafe.sol --pkg $(PACKAGE) --out $(GO_OUT_MULTISIGN)/gnosisSafe.go
bep20Bin:
@abigen --sol $(SRC_BEP)/BEP20.sol --pkg $(PACKAGE) --out $(GO_OUT_BEP20)/bep20.go
erc20Bin:
@abigen --sol $(SRC_ERC20)/ERC20.sol --pkg $(PACKAGE) --out $(GO_OUT_ERC20)/erc20.go
clean:
@rm -fr $(GO_OUT)/*
......
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -21,6 +21,8 @@ contract BridgeBank is Chain33Bank, EthereumBank {
address public operator;
Oracle public oracle;
Chain33Bridge public chain33Bridge;
string public platformTokenSymbol;
bool public hasSetPlatformTokenSymbol;
/*
* @dev: Constructor, sets operator
......@@ -193,12 +195,25 @@ contract BridgeBank is Chain33Bank, EthereumBank {
if (address(0) != _token) {
require(keccak256(bytes(BridgeToken(_token).symbol())) == keccak256(bytes(_symbol)), "token address and symbol is not consistent");
} else {
require(keccak256(bytes("ETH")) == keccak256(bytes(_symbol)), "token address and symbol is not consistent");
require(true == hasSetPlatformTokenSymbol, "The platform Token Symbol has not been configured");
require(keccak256(bytes(platformTokenSymbol)) == keccak256(bytes(_symbol)), "token address and symbol is not consistent");
}
configOfflineSave4Lock(_token, _symbol, _threshold, _percents);
}
/*
* @dev: configplatformTokenSymbol used to config platform token symbol,and just could be configured once
*
* @param _symbol:token symbol,just used for double check that token address and symbol is consistent
*/
function configplatformTokenSymbol(string memory _symbol) public onlyOperator
{
require(false == hasSetPlatformTokenSymbol, "The platform Token Symbol has been configured");
platformTokenSymbol = _symbol;
hasSetPlatformTokenSymbol = true;
}
/*
* @dev: configOfflineSaveAccount used to config offline account to receive token
* when the balance of locked token reaches threshold
*
......@@ -237,9 +252,9 @@ contract BridgeBank is Chain33Bank, EthereumBank {
msg.value == _amount,
"The transactions value must be equal the specified amount (in wei)"
);
require(true == hasSetPlatformTokenSymbol, "The platform Token Symbol has not been configured");
// Set the the symbol to ETH
symbol = "ETH";
symbol = platformTokenSymbol;
// ERC20 deposit
} else {
require(
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -15,6 +15,7 @@ contract ERC20 is Context, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}.
......@@ -25,10 +26,11 @@ contract ERC20 is Context, IERC20 {
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_,uint256 supply, address owner) {
constructor (string memory name_, string memory symbol_,uint256 supply, address owner, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_totalSupply=supply;
_decimals = decimals_;
_balances[owner] = supply;
}
......@@ -61,7 +63,7 @@ contract ERC20 is Context, IERC20 {
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 8;
return _decimals;
}
/**
......
......@@ -252,6 +252,12 @@ func TestBridgeDepositLock(t *testing.T) {
sim.Commit()
t.Logf("The new creaded symbol:%s, address:%s", symbol, bridgeTokenAddr.String())
userAuth, err := ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.ConfigplatformTokenSymbol(userAuth, "ETH")
require.Nil(t, err)
sim.Commit()
operatorAuth, err = ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.AddToken2LockList(operatorAuth, bridgeTokenAddr, symbol)
......@@ -355,6 +361,12 @@ func TestBridgeBankUnlock(t *testing.T) {
userOneAuth, err := ethtxs.PrepareAuth(sim, para.ValidatorPriKey[0], para.InitValidators[0])
require.Nil(t, err)
userAuth, err := ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.ConfigplatformTokenSymbol(userAuth, "ETH")
require.Nil(t, err)
sim.Commit()
ethLockAmount := big.NewInt(150)
userOneAuth.Value = ethLockAmount
chain33Sender := []byte("14KEKbYtKKQm4wMthSK9J4La4nAiidGozt")
......@@ -499,6 +511,12 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) {
para, sim, x2EthContracts, x2EthDeployInfo, err := setup.DeployContracts()
require.NoError(t, err)
userAuth, err := ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.ConfigplatformTokenSymbol(userAuth, "ETH")
require.Nil(t, err)
sim.Commit()
//1.lockEth资产
ethAddr := common.Address{}
userOneAuth, err := ethtxs.PrepareAuth(sim, para.ValidatorPriKey[0], para.InitValidators[0])
......@@ -647,6 +665,12 @@ func TestBridgeBankSedondUnlockErc20(t *testing.T) {
para, sim, x2EthContracts, x2EthDeployInfo, err := setup.DeployContracts()
require.NoError(t, err)
userAuth, err := ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.ConfigplatformTokenSymbol(userAuth, "ETH")
require.Nil(t, err)
sim.Commit()
//1.lockEth资产
userOneAuth, err := ethtxs.PrepareAuth(sim, para.ValidatorPriKey[0], para.InitValidators[0])
require.Nil(t, err)
......
......@@ -46,6 +46,7 @@ func EthereumRelayerCmd() *cobra.Command {
TokenCmd(),
MultiSignEthCmd(),
TransferEthCmd(),
ConfigplatformTokenSymbolCmd(),
)
return cmd
......@@ -311,6 +312,8 @@ func DeployERC20Flags(cmd *cobra.Command) {
_ = cmd.MarkFlagRequired("symbol")
cmd.Flags().StringP("amount", "m", "0", "amount")
_ = cmd.MarkFlagRequired("amount")
cmd.Flags().Uint8P("decimals", "d", 8, "default set to 8, and can't be greater than 18")
}
func DeployERC20(cmd *cobra.Command, args []string) {
......@@ -319,12 +322,19 @@ func DeployERC20(cmd *cobra.Command, args []string) {
name, _ := cmd.Flags().GetString("name")
symbol, _ := cmd.Flags().GetString("symbol")
amount, _ := cmd.Flags().GetString("amount")
decimals, _ := cmd.Flags().GetUint8("decimals")
if decimals > 18 {
fmt.Println("decimals can't be greater than 18")
return
}
para := ebTypes.ERC20Token{
Owner: owner,
Name: name,
Symbol: symbol,
Amount: amount,
Decimals: int32(decimals),
}
var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.DeployERC20", para, &res)
......@@ -971,6 +981,33 @@ func ConfigOfflineSaveAccount(cmd *cobra.Command, args []string) {
ctx.Run()
}
//ConfigplatformTokenSymbolCmd ...
func ConfigplatformTokenSymbolCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "set_symbol",
Short: "save config symbol",
Run: ConfigplatformTokenSymbol,
}
ConfigplatformTokenSymbolFlags(cmd)
return cmd
}
//ConfigplatformTokenSymbolFlags ...
func ConfigplatformTokenSymbolFlags(cmd *cobra.Command) {
cmd.Flags().StringP("symbol", "s", "ETH", "symbol")
_ = cmd.MarkFlagRequired("symbol")
}
//ConfigplatformTokenSymbol ...
func ConfigplatformTokenSymbol(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
symbol, _ := cmd.Flags().GetString("symbol")
var res rpctypes.Reply
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Manager.ConfigplatformTokenSymbol", symbol, &res)
ctx.Run()
}
//ConfigLockedTokenOfflineSaveCmd ...
func ConfigLockedTokenOfflineSaveCmd() *cobra.Command {
cmd := &cobra.Command{
......
......@@ -102,7 +102,7 @@ func main() {
relayerManager := relayer.NewRelayerManager(chain33RelayerService, ethRelayerService, db)
mainlog.Info("cfg.JrpcBindAddr = ", cfg.JrpcBindAddr)
mainlog.Info("ebrelayer", "cfg.JrpcBindAddr = ", cfg.JrpcBindAddr)
startRPCServer(cfg.JrpcBindAddr, relayerManager)
ch := make(chan os.Signal, 1)
......
......@@ -183,6 +183,7 @@ message TokenAddress {
string address = 1;
string symbol = 2;
string chainName = 3;
int32 decimal = 4;
}
message TokenAddressArray {
......@@ -221,6 +222,7 @@ message ERC20Token {
string name = 2;
string symbol = 3;
string amount = 4;
int32 decimals = 5;
}
message ETHTokenLockAddress {
......
......@@ -406,10 +406,25 @@ func (chain33Relayer *Relayer4Chain33) relayLockBurnToChain33(claim *ebTypes.Eth
}
}
//因为发行的合约的精度为8,所以需要缩小,在进行burn的时候,再进行倍乘,在函数ParseBurnLock4chain33进行
if ebTypes.SYMBOL_ETH == claim.Symbol {
bigAmount.Div(bigAmount, big.NewInt(int64(1e10)))
//因为发行的合约的精度为8,所以需要进行相应的缩放
if 8 != claim.Decimal {
if claim.Decimal > 8 {
dist := claim.Decimal - 8
value, exist := utils.Decimal2value[int(dist)]
if !exist {
panic(fmt.Sprintf("does support for decimal, %d", claim.Decimal))
}
bigAmount.Div(bigAmount, big.NewInt(value))
claim.Amount = bigAmount.String()
} else {
dist := 8 - claim.Decimal
value, exist := utils.Decimal2value[int(dist)]
if !exist {
panic(fmt.Sprintf("does support for decimal, %d", claim.Decimal))
}
bigAmount.Mul(bigAmount, big.NewInt(value))
claim.Amount = bigAmount.String()
}
}
parameter := fmt.Sprintf("newOracleClaim(%d, %s, %s, %s, %s, %s, %s, %s)",
......
......@@ -71,7 +71,7 @@ type Relayer4Ethereum struct {
chain33MsgChan <-chan *events.Chain33Msg
totalTxRelayFromChain33 int64
symbol2Addr map[string]common.Address
symbol2LockAddr map[string]common.Address
symbol2LockAddr map[string]ebTypes.TokenAddress
mulSignAddr string
}
......@@ -111,7 +111,7 @@ func StartEthereumRelayer(startPara *EthereumStartPara) *Relayer4Ethereum {
chain33MsgChan: startPara.Chain33MsgChan,
totalTxRelayFromChain33: 0,
symbol2Addr: make(map[string]common.Address),
symbol2LockAddr: make(map[string]common.Address),
symbol2LockAddr: make(map[string]ebTypes.TokenAddress),
}
registrAddrInDB, err := ethRelayer.getBridgeRegistryAddr()
......@@ -332,12 +332,12 @@ func (ethRelayer *Relayer4Ethereum) AddToken2LockList(symbol, token string) (str
}
//DeployERC20 ...
func (ethRelayer *Relayer4Ethereum) DeployERC20(ownerAddr, name, symbol, amount string) (string, error) {
func (ethRelayer *Relayer4Ethereum) DeployERC20(ownerAddr, name, symbol, amount string, decimals uint8) (string, error) {
bn := big.NewInt(1)
bn, _ = bn.SetString(utils.TrimZeroAndDot(amount), 10)
ethRelayer.rwLock.RLock()
defer ethRelayer.rwLock.RUnlock()
return ethtxs.DeployERC20(ownerAddr, name, symbol, bn, ethRelayer.clientSpec, ethRelayer.operatorInfo)
return ethtxs.DeployERC20(ownerAddr, name, symbol, bn, decimals, ethRelayer.clientSpec, ethRelayer.operatorInfo)
}
//ApproveAllowance ...
......@@ -496,23 +496,34 @@ func (ethRelayer *Relayer4Ethereum) handleChain33Msg(chain33Msg *events.Chain33M
tokenAddr = common.HexToAddress(addr)
}
} else {
tokenAddr, exist = ethRelayer.symbol2LockAddr[prophecyClaim.Symbol]
burnFromChain33TokenInfo, exist := ethRelayer.symbol2LockAddr[prophecyClaim.Symbol]
if !exist {
//因为是burn操作,必须从允许lock的token地址中进行查询
addr, err := ethRelayer.ShowLockedTokenAddress(prophecyClaim.Symbol)
if err != nil {
panic(fmt.Sprintf("Pls create lock token in advance for token:%s", prophecyClaim.Symbol))
relayerLog.Error("handleChain33Msg", "Failed to fetch locked Token Info for symbol", prophecyClaim.Symbol)
return
}
token2set := ebTypes.TokenAddress{
Address: addr,
Symbol: prophecyClaim.Symbol,
ChainName: ebTypes.EthereumBlockChainName,
tokenAddr = common.HexToAddress(burnFromChain33TokenInfo.Address)
//if lockedTokenInfo.Decimal == 18 {
// prophecyClaim.Amount = prophecyClaim.Amount.Mul(prophecyClaim.Amount, big.NewInt(int64(1e10)))
//}
//从chain33进行withdraw回来的token需要根据精度进行相应的缩放
if 8 != burnFromChain33TokenInfo.Decimal {
if burnFromChain33TokenInfo.Decimal > 8 {
dist := burnFromChain33TokenInfo.Decimal - 8
value, exist := utils.Decimal2value[int(dist)]
if !exist {
panic(fmt.Sprintf("does support for decimal, %d", burnFromChain33TokenInfo.Decimal))
}
err = ethRelayer.SetLockedTokenAddress(token2set)
if nil != err {
relayerLog.Error("handleChain33Msg", "Failed to SetLockedTokenAddress due to", err.Error())
prophecyClaim.Amount.Mul(prophecyClaim.Amount, big.NewInt(value))
} else {
dist := 8 - burnFromChain33TokenInfo.Decimal
value, exist := utils.Decimal2value[int(dist)]
if !exist {
panic(fmt.Sprintf("does support for decimal, %d", burnFromChain33TokenInfo.Decimal))
}
prophecyClaim.Amount.Div(prophecyClaim.Amount, big.NewInt(value))
}
tokenAddr = common.HexToAddress(addr)
}
}
......@@ -800,7 +811,7 @@ func (ethRelayer *Relayer4Ethereum) subscribeEvent() {
// Filter by contract and event, write results to logs
sub, err := ethRelayer.clientSpec.SubscribeFilterLogs(context.Background(), query, logs)
if err != nil {
errinfo := fmt.Sprintf("Failed to SubscribeFilterLogs due to:%s", err.Error())
errinfo := fmt.Sprintf("Failed to SubscribeFilterLogs due to:%s, bridgeBankAddr:%s", err.Error(), ethRelayer.bridgeBankAddr)
panic(errinfo)
}
relayerLog.Info("subscribeEvent", "Subscribed to contract at address:", targetAddress.Hex())
......@@ -860,6 +871,21 @@ func (ethRelayer *Relayer4Ethereum) handleLogLockEvent(clientChainID *big.Int, c
}
}
tokenLocked, err := ethRelayer.GetLockedTokenAddress(event.Symbol)
if nil == tokenLocked {
token2set := &ebTypes.TokenAddress{
Address: event.Token.String(),
Symbol: event.Symbol,
ChainName: ebTypes.EthereumBlockChainName,
Decimal: int32(decimal),
}
err = ethRelayer.SetLockedTokenAddress(token2set)
if nil != err {
relayerLog.Error("handleChain33Msg", "Failed to SetLockedTokenAddress due to", err.Error())
return errors.New("Failed ")
}
}
// Parse the LogLock event's payload into a struct
prophecyClaim, err := ethtxs.LogLockToEthBridgeClaim(event, clientChainID.Int64(), ethRelayer.bridgeBankAddr.String(), log.TxHash.String(), int64(decimal))
if err != nil {
......@@ -995,6 +1021,11 @@ func (ethRelayer *Relayer4Ethereum) ConfigOfflineSaveAccount(addr string) (strin
return txhash, err
}
func (ethRelayer *Relayer4Ethereum) ConfigplatformTokenSymbol(symbol string) (string, error) {
txhash, err := ethtxs.ConfigplatformTokenSymbol(symbol, ethRelayer.clientSpec, ethRelayer.operatorInfo, ethRelayer.x2EthContracts)
return txhash, err
}
func (ethRelayer *Relayer4Ethereum) ConfigLockedTokenOfflineSave(addr, symbol, threshold string, percents uint32) (string, error) {
bn := big.NewInt(1)
bn, _ = bn.SetString(utils.TrimZeroAndDot(threshold), 10)
......
......@@ -245,6 +245,12 @@ func Test_LockEth(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, bridgeBankBalance.Int64(), int64(0))
userAuth, err := ethtxs.PrepareAuth(sim, para.DeployPrivateKey, para.Operator)
require.Nil(t, err)
_, err = x2EthContracts.BridgeBank.ConfigplatformTokenSymbol(userAuth, "ETH")
require.Nil(t, err)
sim.Commit()
userOneAuth, err := ethtxs.PrepareAuth(sim, para.ValidatorPriKey[0], para.InitValidators[0])
require.Nil(t, err)
......@@ -414,7 +420,7 @@ func newEthRelayer(para *ethtxs.DeployPara, sim *ethinterface.SimExtend, x2EthCo
fetchHeightPeriodMs: cfg.EthBlockFetchPeriod,
totalTxRelayFromChain33: 0,
symbol2Addr: make(map[string]common.Address),
symbol2LockAddr: make(map[string]common.Address),
symbol2LockAddr: make(map[string]ebTypes.TokenAddress),
ethBridgeClaimChan: ethBridgeClaimchan,
chain33MsgChan: chain33Msgchan,
......
......@@ -359,7 +359,7 @@ func TransferEth(fromPrivateKeyStr, toAddr string, amount *big.Int, client ethin
prepareDone = true
gasLimit := uint64(21000)
gasLimit := uint64(21100)
toAddress := common.HexToAddress(toAddr)
//var data []byte
......@@ -760,6 +760,48 @@ func ConfigOfflineSaveAccount(addr string, client ethinterface.EthClientSpec, pa
return tx.Hash().String(), nil
}
func ConfigplatformTokenSymbol(symbol string, client ethinterface.EthClientSpec, para *OperatorInfo, x2EthContracts *X2EthContracts) (string, error) {
txslog.Info("ConfigplatformTokenSymbol", "symbol", symbol)
if nil == para {
return "", errors.New("no operator private key configured")
}
var prepareDone bool
var err error
defer func() {
if err != nil && prepareDone {
_, _ = revokeNonce(para.Address)
}
}()
auth, err := PrepareAuth(client, para.PrivateKey, para.Address)
if nil != err {
return "", err
}
prepareDone = true
tx, err := x2EthContracts.BridgeBank.BridgeBankTransactor.ConfigplatformTokenSymbol(auth, symbol)
if nil != err {
return "", err
}
sim, isSim := client.(*ethinterface.SimExtend)
if isSim {
fmt.Println("Use the simulator")
sim.Commit()
}
txslog.Info("ConfigplatformTokenSymbol", "tx.Hash()", tx.Hash().String())
err = waitEthTxFinished(client, tx.Hash(), "ConfigplatformTokenSymbol")
if nil != err {
return "", err
}
return tx.Hash().String(), nil
}
func ConfigLockedTokenOfflineSave(addr, symbol string, threshold *big.Int, percents uint8, client ethinterface.EthClientSpec, para *OperatorInfo, x2EthContracts *X2EthContracts) (string, error) {
txslog.Info("ConfigLockedTokenOfflineSave", "addr", addr, "symbol", symbol, "threshold", threshold, "percents", percents)
if nil == para {
......
......@@ -99,10 +99,10 @@ func (c *suiteContracts) Test_LogLockToEthBridgeClaim() {
assert.Equal(c.T(), witnessClaim.Nonce, event.Nonce.Int64())
assert.Equal(c.T(), witnessClaim.Decimal, int64(18))
event.Token = common.HexToAddress("0x0000000000000000000000000000000000000001")
event.To = nil
_, err = LogLockToEthBridgeClaim(event, 1, c.x2EthDeployInfo.BridgeBank.Address.String(), "", 18)
require.NotNil(c.T(), err)
assert.Equal(c.T(), err, ebrelayerTypes.ErrAddress4Eth)
assert.Equal(c.T(), err, ebrelayerTypes.ErrEmptyAddress)
}
func (c *suiteContracts) Test_LogBurnToEthBridgeClaim() {
......
......@@ -196,7 +196,7 @@ func DeployAndInit(client ethinterface.EthClientSpec, para *DeployPara) (*X2EthC
case <-oneSecondtimeout.C:
_, err := client.TransactionReceipt(context.Background(), common.HexToHash(deployInfo.Valset.TxHash))
if err == ethereum.NotFound {
fmt.Println("\n No receipt received yet for DeployValset tx and continue to wait")
//fmt.Println("\n No receipt received yet for DeployValset tx and continue to wait")
continue
} else if err != nil {
panic("DeployValset failed due to" + err.Error())
......@@ -499,7 +499,7 @@ finished:
return x2EthContracts, deployInfo, nil
}
func DeployERC20(ownerAddr, name, symbol string, amount *big.Int, client ethinterface.EthClientSpec, para *OperatorInfo) (string, error) {
func DeployERC20(ownerAddr, name, symbol string, amount *big.Int, decimals uint8, client ethinterface.EthClientSpec, para *OperatorInfo) (string, error) {
if nil == para {
return "", errors.New("no operator private key configured")
}
......@@ -523,7 +523,7 @@ func DeployERC20(ownerAddr, name, symbol string, amount *big.Int, client ethinte
txslog.Info("DeployERC20", "ownerAddr", ownerAddr, "name", name, "symbol", symbol, "amount", amount, "client", client)
Erc20OwnerAddr := common.HexToAddress(ownerAddr)
Erc20Addr, deployTx, _, err := erc20.DeployERC20(operatorAuth, client, name, symbol, amount, Erc20OwnerAddr)
Erc20Addr, deployTx, _, err := erc20.DeployERC20(operatorAuth, client, name, symbol, amount, Erc20OwnerAddr, decimals)
if nil != err {
txslog.Error("DeployERC20", "Failed to DeployErc20 with err:", err.Error())
return "", err
......
......@@ -29,9 +29,9 @@ func SetupWebsocketEthClient(ethURL string) (*ethclient.Client, error) {
return nil, nil
}
if !isWebsocketURL(ethURL) {
return nil, fmt.Errorf("invalid websocket eth client URL: %v", ethURL)
}
//if !isWebsocketURL(ethURL) {
// return nil, fmt.Errorf("invalid websocket eth client URL: %v", ethURL)
//}
client, err := ethclient.Dial(ethURL)
if err != nil {
......
......@@ -10,12 +10,9 @@ package ethtxs
// --------------------------------------------------------
import (
"strings"
"github.com/33cn/chain33/common/address"
"github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/relayer/events"
ebrelayerTypes "github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/types"
"github.com/ethereum/go-ethereum/common"
)
// LogLockToEthBridgeClaim : parses and packages a LockEvent struct with a validator address in an EthBridgeClaim msg
......@@ -24,11 +21,6 @@ func LogLockToEthBridgeClaim(event *events.LockEvent, ethereumChainID int64, bri
if 0 == len(recipient) {
return nil, ebrelayerTypes.ErrEmptyAddress
}
// Symbol formatted to lowercase
symbol := strings.ToLower(event.Symbol)
if symbol == "eth" && event.Token != common.HexToAddress("0x0000000000000000000000000000000000000000") {
return nil, ebrelayerTypes.ErrAddress4Eth
}
chain33Receiver := new(address.Address)
chain33Receiver.SetBytes(recipient)
......
......@@ -4,6 +4,7 @@ import (
"context"
"errors"
bep20 "github.com/33cn/plugin/plugin/dapp/cross2eth/contracts/bep20/generated"
"github.com/33cn/plugin/plugin/dapp/cross2eth/contracts/contracts4eth/generated"
"github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethinterface"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
......@@ -75,7 +76,7 @@ func IsProphecyPending(claimID [32]byte, validator common.Address, chain33Bridge
func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (string, error) {
//查询ERC20余额
if tokenAddr != "" {
bridgeToken, err := generated.NewBridgeToken(common.HexToAddress(tokenAddr), client)
bep20Token, err := bep20.NewBEP20Token(common.HexToAddress(tokenAddr), client)
if nil != err {
txslog.Error("GetBalance", "generated.NewBridgeToken err:", err.Error(), "tokenAddr", tokenAddr, "owner", owner)
return "", err
......@@ -86,7 +87,7 @@ func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (str
From: ownerAddr,
Context: context.Background(),
}
balance, err := bridgeToken.BalanceOf(opts, ownerAddr)
balance, err := bep20Token.BalanceOf(opts, ownerAddr)
if nil != err {
txslog.Error("GetBalance", "bridgeToken.BalanceOf err:", err.Error(), "tokenAddr", tokenAddr, "owner", owner)
return "", err
......
......@@ -244,20 +244,32 @@ func (ethRelayer *Relayer4Ethereum) SetTokenAddress(token2set ebTypes.TokenAddre
return ethRelayer.db.Set(ethTokenSymbol2AddrKey(token2set.Symbol), bytes)
}
func (ethRelayer *Relayer4Ethereum) SetLockedTokenAddress(token2set ebTypes.TokenAddress) error {
addr := common.HexToAddress(token2set.Address)
bytes := chain33Types.Encode(&token2set)
func (ethRelayer *Relayer4Ethereum) SetLockedTokenAddress(token2set *ebTypes.TokenAddress) error {
bytes := chain33Types.Encode(token2set)
ethRelayer.rwLock.Lock()
ethRelayer.symbol2LockAddr[token2set.Symbol] = addr
ethRelayer.symbol2LockAddr[token2set.Symbol] = *token2set
ethRelayer.rwLock.Unlock()
return ethRelayer.db.Set(ethTokenSymbol2LockAddrKey(token2set.Symbol), bytes)
}
func (ethRelayer *Relayer4Ethereum) GetLockedTokenAddress(symbol string) (*ebTypes.TokenAddress, error) {
ethRelayer.rwLock.RLock()
data, err := ethRelayer.db.Get(ethTokenSymbol2LockAddrKey(symbol))
ethRelayer.rwLock.RUnlock()
if nil != err {
return nil, err
}
var token2set ebTypes.TokenAddress
if err := chain33Types.Decode(data, &token2set); nil != err {
return nil, err
}
return &token2set, err
}
func (ethRelayer *Relayer4Ethereum) RestoreTokenAddress() error {
ethRelayer.rwLock.Lock()
defer ethRelayer.rwLock.Unlock()
ethRelayer.symbol2LockAddr[ebTypes.SYMBOL_ETH] = common.HexToAddress(ebTypes.EthNilAddr)
helper := dbm.NewListHelper(ethRelayer.db)
datas := helper.List(ethTokenSymbol2AddrPrefix, nil, 100, dbm.ListASC)
......@@ -273,13 +285,13 @@ func (ethRelayer *Relayer4Ethereum) RestoreTokenAddress() error {
datas = helper.List(ethTokenSymbol2LockAddrPrefix, nil, 100, dbm.ListASC)
for _, data := range datas {
var token2set ebTypes.TokenAddress
err := chain33Types.Decode(data, &token2set)
var tokenLocked ebTypes.TokenAddress
err := chain33Types.Decode(data, &tokenLocked)
if nil != err {
return err
}
relayerLog.Info("RestoreTokenAddress", "symbol", token2set.Symbol, "address", token2set.Address)
ethRelayer.symbol2LockAddr[token2set.Symbol] = common.HexToAddress(token2set.Address)
relayerLog.Info("RestoreTokenAddress", "symbol", tokenLocked.Symbol, "address", tokenLocked.Address)
ethRelayer.symbol2LockAddr[tokenLocked.Symbol] = tokenLocked
}
return nil
}
......
......@@ -132,9 +132,6 @@ func ParseBurnLock4chain33(evmEventType Chain33EvmEvent, data []byte, bridgeBank
TxHash: chain33TxHash,
Nonce: burnEvent.Nonce.Int64(),
}
if ebrelayerTypes.SYMBOL_ETH == burnEvent.Symbol {
chain33Msg.Amount = chain33Msg.Amount.Mul(chain33Msg.Amount, big.NewInt(int64(1e10)))
}
return chain33Msg, nil
}
......
......@@ -485,7 +485,7 @@ func (manager *Manager) DeployERC20(Erc20Token relayerTypes.ERC20Token, result *
return err
}
Erc20Addr, err := manager.ethRelayer.DeployERC20(Erc20Token.Owner, Erc20Token.Name, Erc20Token.Symbol, Erc20Token.Amount)
Erc20Addr, err := manager.ethRelayer.DeployERC20(Erc20Token.Owner, Erc20Token.Name, Erc20Token.Symbol, Erc20Token.Amount, uint8(Erc20Token.Decimals))
if nil != err {
return err
}
......@@ -996,6 +996,23 @@ func (manager *Manager) ConfigOfflineSaveAccount(addr string, result *interface{
return nil
}
func (manager *Manager) ConfigplatformTokenSymbol(symbol string, result *interface{}) error {
manager.mtx.Lock()
defer manager.mtx.Unlock()
if err := manager.checkPermission(); nil != err {
return err
}
txhash, err := manager.ethRelayer.ConfigplatformTokenSymbol(symbol)
if nil != err {
return err
}
*result = rpctypes.Reply{
IsOk: true,
Msg: txhash,
}
return nil
}
func (manager *Manager) ConfigLockedTokenOfflineSave(config relayerTypes.ETHConfigLockedTokenOffline, result *interface{}) error {
manager.mtx.Lock()
defer manager.mtx.Unlock()
......
......@@ -34,6 +34,20 @@ const (
nullAddress = "0x0000000000000000000000000000000000000000"
)
var Decimal2value = map[int]int64{
1: 1e1,
2: 1e2,
3: 1e3,
4: 1e4,
5: 1e5,
6: 1e6,
7: 1e7,
8: 1e8,
9: 1e9,
10: 1e10,
11: 1e11,
}
var log = log15.New("module", "utils")
// IsZeroAddress : checks an Ethereum address and returns a bool which indicates if it is the null address
......@@ -242,7 +256,7 @@ func ToWei(amount float64, decimal int64) *big.Int {
var ok bool
bn := big.NewInt(1)
if decimal > 4 {
bn, ok = bn.SetString(TrimZeroAndDot(fmt.Sprintf("%.0f", MultiplySpecifyTimes(math.Trunc(amount*1e4), decimal-4))), 10)
bn, ok = bn.SetString(TrimZeroAndDot(fmt.Sprintf("%.0f", MultiplySpecifyTimes(math.Trunc(amount*1e4+0.0000000000001), decimal-4))), 10)
} else {
bn, ok = bn.SetString(TrimZeroAndDot(fmt.Sprintf("%.0f", MultiplySpecifyTimes(amount, decimal))), 10)
}
......
package utils
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func Test_decimals(t *testing.T) {
value2comp := 10
for i := 1; i <= 10; i++ {
value, ok := Decimal2value[i]
require.Equal(t, value, int64(value2comp))
require.Equal(t, ok, true)
fmt.Println("value=", value)
value2comp = value2comp * 10
}
}
......@@ -21,8 +21,8 @@ func main() {
buildFlags.RPCAddr4Chain33 = testTLS(buildFlags.RPCAddr4Chain33)
if buildFlags.RPCAddr4Ethereum == "" {
//buildFlags.RPCAddr4Ethereum = "https://data-seed-prebsc-1-s1.binance.org:8545"
buildFlags.RPCAddr4Ethereum = "wss://ws-testnet.huobichain.com"
buildFlags.RPCAddr4Ethereum = "https://data-seed-prebsc-1-s1.binance.org:8545"
//buildFlags.RPCAddr4Ethereum = "wss://ws-testnet.huobichain.com"
}
rootCmd := RootCmd()
......
......@@ -53,7 +53,6 @@ func (s *SignCmd) addFlags(cmd *cobra.Command) {
cmd.MarkFlagRequired("nonce")
cmd.Flags().Int64P("gasprice", "g", 1000000000, "gas price") // 1Gwei=1e9wei
cmd.MarkFlagRequired("gasprice")
}
func (s *SignCmd) signContract(cmd *cobra.Command, args []string) {
......@@ -270,7 +269,6 @@ func (s *SignPanCakeRout) reWriteDeployPanCakeRout(nonce uint64, gasPrice *big.I
var amount = new(big.Int)
ntx := types.NewContractCreation(nonce, amount, gasLimit, gasPrice, data)
return SignTx(key, ntx)
}
func SignTx(key *ecdsa.PrivateKey, tx *types.Transaction) (signedTx, hash string, err error) {
......@@ -293,6 +291,26 @@ func SignTx(key *ecdsa.PrivateKey, tx *types.Transaction) (signedTx, hash string
return
}
func SignEIP155Tx(key *ecdsa.PrivateKey, tx *types.Transaction, chainEthId int64) (signedTx, hash string, err error) {
signer := types.NewEIP155Signer(big.NewInt(chainEthId))
txhash := signer.Hash(tx)
signature, err := crypto.Sign(txhash.Bytes(), key)
if err != nil {
return
}
tx, err = tx.WithSignature(signer, signature)
if err != nil {
return
}
txBinary, err := tx.MarshalBinary()
if err != nil {
return
}
hash = tx.Hash().String()
signedTx = common.Bytes2Hex(txBinary[:])
return
}
func recoverBinancePrivateKey(key string) (priv *ecdsa.PrivateKey, address common.Address, err error) {
//louyuqi: f726c7c704e57ec5d59815dda23ddd794f71ae15f7e0141f00f73eff35334ac6
//hzj: 2bcf3e23a17d3f3b190a26a098239ad2d20267a673440e0f57a23f44f94b77b9
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment