mirror of
https://github.com/AthanorLabs/atomic-swap.git
synced 2026-01-08 21:58:07 -05:00
SwapFactory to SwapCreator rename, upgrade to solc 0.8.19 (#372)
This commit is contained in:
1
.github/workflows/unit-tests.yml
vendored
1
.github/workflows/unit-tests.yml
vendored
@@ -59,6 +59,7 @@ jobs:
|
|||||||
- name: Run unit tests
|
- name: Run unit tests
|
||||||
env:
|
env:
|
||||||
ETH_MAINNET_ENDPOINT: ${{ secrets.ETH_MAINNET_ENDPOINT }}
|
ETH_MAINNET_ENDPOINT: ${{ secrets.ETH_MAINNET_ENDPOINT }}
|
||||||
|
ETH_SEPOLIA_ENDPOINT: ${{ secrets.ETH_SEPOLIA_ENDPOINT }}
|
||||||
run: ./scripts/run-unit-tests.sh
|
run: ./scripts/run-unit-tests.sh
|
||||||
|
|
||||||
- name: Upload code coverage
|
- name: Upload code coverage
|
||||||
|
|||||||
@@ -30,87 +30,87 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type contractAddresses struct {
|
type contractAddresses struct {
|
||||||
SwapFactory ethcommon.Address `json:"swapFactory" validate:"required"`
|
SwapCreatorAddr ethcommon.Address `json:"swapCreatorAddr" validate:"required"`
|
||||||
Forwarder ethcommon.Address `json:"forwarder" validate:"required"`
|
ForwarderAddr ethcommon.Address `json:"forwarderAddr" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func getOrDeploySwapFactory(
|
func getOrDeploySwapCreator(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
address ethcommon.Address,
|
swapCreatorAddr ethcommon.Address,
|
||||||
env common.Environment,
|
env common.Environment,
|
||||||
dataDir string,
|
dataDir string,
|
||||||
ec extethclient.EthClient,
|
ec extethclient.EthClient,
|
||||||
forwarderAddress ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
) (ethcommon.Address, error) {
|
) (ethcommon.Address, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if env != common.Mainnet && (address == ethcommon.Address{}) {
|
if env != common.Mainnet && (swapCreatorAddr == ethcommon.Address{}) {
|
||||||
// we're on a development or testnet environment and we have no deployed contract,
|
// we're on a development or testnet environment and we have no deployed contract,
|
||||||
// so let's deploy one
|
// so let's deploy one
|
||||||
address, _, err = deploySwapFactory(ctx, ec.Raw(), ec.PrivateKey(), forwarderAddress, dataDir)
|
swapCreatorAddr, _, err = deploySwapCreator(ctx, ec.Raw(), ec.PrivateKey(), forwarderAddr, dataDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, fmt.Errorf("failed to deploy swap factory: %w", err)
|
return ethcommon.Address{}, fmt.Errorf("failed to deploy swap creator: %w", err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// otherwise, load the contract from the given address
|
// otherwise, load the contract from the given address
|
||||||
// and check that its bytecode is valid (ie. matches the
|
// and check that its bytecode is valid (ie. matches the
|
||||||
// bytecode of this repo's swap contract)
|
// bytecode of this repo's swap contract)
|
||||||
_, err = contracts.CheckSwapFactoryContractCode(ctx, ec.Raw(), address)
|
_, err = contracts.CheckSwapCreatorContractCode(ctx, ec.Raw(), swapCreatorAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, err
|
return ethcommon.Address{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return address, nil
|
return swapCreatorAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func deploySwapFactory(
|
func deploySwapCreator(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
privkey *ecdsa.PrivateKey,
|
privkey *ecdsa.PrivateKey,
|
||||||
forwarderAddress ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
dataDir string,
|
dataDir string,
|
||||||
) (ethcommon.Address, *contracts.SwapFactory, error) {
|
) (ethcommon.Address, *contracts.SwapCreator, error) {
|
||||||
|
|
||||||
if privkey == nil {
|
if privkey == nil {
|
||||||
return ethcommon.Address{}, nil, errNoEthereumPrivateKey
|
return ethcommon.Address{}, nil, errNoEthereumPrivateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
if (forwarderAddress == ethcommon.Address{}) {
|
if (forwarderAddr == ethcommon.Address{}) {
|
||||||
// deploy forwarder contract as well
|
// deploy forwarder contract as well
|
||||||
var err error
|
var err error
|
||||||
forwarderAddress, err = contracts.DeployGSNForwarderWithKey(ctx, ec, privkey)
|
forwarderAddr, err = contracts.DeployGSNForwarderWithKey(ctx, ec, privkey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, nil, err
|
return ethcommon.Address{}, nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := contracts.CheckForwarderContractCode(ctx, ec, forwarderAddress); err != nil {
|
if err := contracts.CheckForwarderContractCode(ctx, ec, forwarderAddr); err != nil {
|
||||||
return ethcommon.Address{}, nil, err
|
return ethcommon.Address{}, nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
swapFactoryAddress, sf, err := contracts.DeploySwapFactoryWithKey(ctx, ec, privkey, forwarderAddress)
|
swapCreatorAddr, sf, err := contracts.DeploySwapCreatorWithKey(ctx, ec, privkey, forwarderAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, nil, err
|
return ethcommon.Address{}, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// store the contract address on disk
|
// store the contract addresses on disk
|
||||||
err = writeContractAddressToFile(
|
err = writeContractAddressesToFile(
|
||||||
path.Join(dataDir, contractAddressesFile),
|
path.Join(dataDir, contractAddressesFile),
|
||||||
&contractAddresses{
|
&contractAddresses{
|
||||||
SwapFactory: swapFactoryAddress,
|
SwapCreatorAddr: swapCreatorAddr,
|
||||||
Forwarder: forwarderAddress,
|
ForwarderAddr: forwarderAddr,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, nil, fmt.Errorf("failed to write contract address to file: %w", err)
|
return ethcommon.Address{}, nil, fmt.Errorf("failed to write contract address to file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return swapFactoryAddress, sf, nil
|
return swapCreatorAddr, sf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeContractAddressToFile writes the contract address to the given file
|
// writeContractAddressesToFile writes the contract addresses to the given file
|
||||||
func writeContractAddressToFile(filePath string, addresses *contractAddresses) error {
|
func writeContractAddressesToFile(filePath string, addresses *contractAddresses) error {
|
||||||
jsonData, err := vjson.MarshalIndentStruct(addresses, "", " ")
|
jsonData, err := vjson.MarshalIndentStruct(addresses, "", " ")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
func TestGetOrDeploySwapCreator_DeployNoForwarder(t *testing.T) {
|
||||||
pk := tests.GetTakerTestKey(t)
|
pk := tests.GetTakerTestKey(t)
|
||||||
ec := extethclient.CreateTestClient(t, pk)
|
ec := extethclient.CreateTestClient(t, pk)
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
@@ -24,7 +24,7 @@ func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
|||||||
forwarder, err := contracts.DeployGSNForwarderWithKey(context.Background(), ec.Raw(), pk)
|
forwarder, err := contracts.DeployGSNForwarderWithKey(context.Background(), ec.Raw(), pk)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
_, err = getOrDeploySwapFactory(
|
_, err = getOrDeploySwapCreator(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
ethcommon.Address{},
|
ethcommon.Address{},
|
||||||
common.Development,
|
common.Development,
|
||||||
@@ -35,12 +35,12 @@ func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetOrDeploySwapFactory_DeployForwarderAlso(t *testing.T) {
|
func TestGetOrDeploySwapCreator_DeployForwarderAlso(t *testing.T) {
|
||||||
pk := tests.GetTakerTestKey(t)
|
pk := tests.GetTakerTestKey(t)
|
||||||
ec := extethclient.CreateTestClient(t, pk)
|
ec := extethclient.CreateTestClient(t, pk)
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
|
|
||||||
_, err := getOrDeploySwapFactory(
|
_, err := getOrDeploySwapCreator(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
ethcommon.Address{},
|
ethcommon.Address{},
|
||||||
common.Development,
|
common.Development,
|
||||||
@@ -51,7 +51,7 @@ func TestGetOrDeploySwapFactory_DeployForwarderAlso(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
func TestGetOrDeploySwapCreator_Get(t *testing.T) {
|
||||||
pk := tests.GetTakerTestKey(t)
|
pk := tests.GetTakerTestKey(t)
|
||||||
ec := extethclient.CreateTestClient(t, pk)
|
ec := extethclient.CreateTestClient(t, pk)
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
@@ -61,7 +61,7 @@ func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
|||||||
t.Log(forwarder)
|
t.Log(forwarder)
|
||||||
|
|
||||||
// deploy and get address
|
// deploy and get address
|
||||||
address, err := getOrDeploySwapFactory(
|
address, err := getOrDeploySwapCreator(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
ethcommon.Address{},
|
ethcommon.Address{},
|
||||||
common.Development,
|
common.Development,
|
||||||
@@ -71,7 +71,7 @@ func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
|||||||
)
|
)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
addr2, err := getOrDeploySwapFactory(
|
addr2, err := getOrDeploySwapCreator(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
address,
|
address,
|
||||||
common.Development,
|
common.Development,
|
||||||
|
|||||||
@@ -151,7 +151,7 @@ func cliApp() *cli.App {
|
|||||||
},
|
},
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: flagContractAddress,
|
Name: flagContractAddress,
|
||||||
Usage: "Address of instance of SwapFactory.sol already deployed on-chain; required if running on mainnet",
|
Usage: "Address of instance of SwapCreator.sol already deployed on-chain; required if running on mainnet",
|
||||||
},
|
},
|
||||||
&cli.StringSliceFlag{
|
&cli.StringSliceFlag{
|
||||||
Name: flagBootnodes,
|
Name: flagBootnodes,
|
||||||
@@ -362,17 +362,17 @@ func getEnvConfig(c *cli.Context, devXMRMaker bool, devXMRTaker bool) (*common.C
|
|||||||
return nil, errFlagsMutuallyExclusive(flagDeploy, flagContractAddress)
|
return nil, errFlagsMutuallyExclusive(flagDeploy, flagContractAddress)
|
||||||
}
|
}
|
||||||
// Zero out the contract address, we'll set its final value after deploying
|
// Zero out the contract address, we'll set its final value after deploying
|
||||||
conf.SwapFactoryAddress = ethcommon.Address{}
|
conf.SwapCreatorAddr = ethcommon.Address{}
|
||||||
} else {
|
} else {
|
||||||
contractAddrStr := c.String(flagContractAddress)
|
contractAddrStr := c.String(flagContractAddress)
|
||||||
if contractAddrStr != "" {
|
if contractAddrStr != "" {
|
||||||
if !ethcommon.IsHexAddress(contractAddrStr) {
|
if !ethcommon.IsHexAddress(contractAddrStr) {
|
||||||
return nil, fmt.Errorf("%q requires a valid ethereum address", flagContractAddress)
|
return nil, fmt.Errorf("%q requires a valid ethereum address", flagContractAddress)
|
||||||
}
|
}
|
||||||
conf.SwapFactoryAddress = ethcommon.HexToAddress(contractAddrStr)
|
conf.SwapCreatorAddr = ethcommon.HexToAddress(contractAddrStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
if conf.SwapFactoryAddress == (ethcommon.Address{}) {
|
if conf.SwapCreatorAddr == (ethcommon.Address{}) {
|
||||||
return nil, fmt.Errorf("flag %q or %q is required for env=%s", flagDeploy, flagContractAddress, env)
|
return nil, fmt.Errorf("flag %q or %q is required for env=%s", flagDeploy, flagContractAddress, env)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -380,42 +380,44 @@ func getEnvConfig(c *cli.Context, devXMRMaker bool, devXMRTaker bool) (*common.C
|
|||||||
return conf, nil
|
return conf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateOrDeployContracts validates or deploys the swap factory. The SwapFactoryAddress field
|
// validateOrDeployContracts validates or deploys the swap creator. The SwapCreatorAddr field
|
||||||
// of envConf should be all zeros if deploying and its value will be replaced by the new deployed
|
// of envConf should be all zeros if deploying and its value will be replaced by the new deployed
|
||||||
// contract.
|
// contract.
|
||||||
func validateOrDeployContracts(c *cli.Context, envConf *common.Config, ec extethclient.EthClient) error {
|
func validateOrDeployContracts(c *cli.Context, envConf *common.Config, ec extethclient.EthClient) error {
|
||||||
deploy := c.Bool(flagDeploy)
|
deploy := c.Bool(flagDeploy)
|
||||||
if deploy && envConf.SwapFactoryAddress != (ethcommon.Address{}) {
|
if deploy && envConf.SwapCreatorAddr != (ethcommon.Address{}) {
|
||||||
panic("contract address should have been zeroed when envConf was initialized")
|
panic("contract address should have been zeroed when envConf was initialized")
|
||||||
}
|
}
|
||||||
|
|
||||||
// forwarderAddress is set only if we're deploying the swap contract, and the --forwarder-address
|
// forwarderAddr is set only if we're deploying the swap creator contract
|
||||||
// flag is set. otherwise, if we're deploying and the flag isn't set, we also deploy the forwarder.
|
// and the --forwarder-address flag is set. Otherwise, if we're deploying
|
||||||
var forwarderAddress ethcommon.Address
|
// and this flag isn't set, we deploy both the forwarder and the swap
|
||||||
forwarderAddressStr := c.String(flagForwarderAddress)
|
// creator contracts.
|
||||||
if deploy && forwarderAddressStr != "" {
|
var forwarderAddr ethcommon.Address
|
||||||
if !ethcommon.IsHexAddress(forwarderAddressStr) {
|
forwarderAddrStr := c.String(flagForwarderAddress)
|
||||||
|
if deploy && forwarderAddrStr != "" {
|
||||||
|
if !ethcommon.IsHexAddress(forwarderAddrStr) {
|
||||||
return fmt.Errorf("%q requires a valid ethereum address", flagForwarderAddress)
|
return fmt.Errorf("%q requires a valid ethereum address", flagForwarderAddress)
|
||||||
}
|
}
|
||||||
|
|
||||||
forwarderAddress = ethcommon.HexToAddress(forwarderAddressStr)
|
forwarderAddr = ethcommon.HexToAddress(forwarderAddrStr)
|
||||||
} else if !deploy && forwarderAddressStr != "" {
|
} else if !deploy && forwarderAddrStr != "" {
|
||||||
return fmt.Errorf("using flag %q requires the %q flag", flagForwarderAddress, flagDeploy)
|
return fmt.Errorf("using flag %q requires the %q flag", flagForwarderAddress, flagDeploy)
|
||||||
}
|
}
|
||||||
|
|
||||||
contractAddr, err := getOrDeploySwapFactory(
|
swapCreatorAddr, err := getOrDeploySwapCreator(
|
||||||
c.Context,
|
c.Context,
|
||||||
envConf.SwapFactoryAddress,
|
envConf.SwapCreatorAddr,
|
||||||
envConf.Env,
|
envConf.Env,
|
||||||
envConf.DataDir,
|
envConf.DataDir,
|
||||||
ec,
|
ec,
|
||||||
forwarderAddress,
|
forwarderAddr,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
envConf.SwapFactoryAddress = contractAddr
|
envConf.SwapCreatorAddr = swapCreatorAddr
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,19 +96,19 @@ func TestDaemon_DevXMRTaker(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
m := make(map[string]string)
|
m := make(map[string]string)
|
||||||
require.NoError(t, json.Unmarshal(data, &m))
|
require.NoError(t, json.Unmarshal(data, &m))
|
||||||
swapFactoryAddr, ok := m["swapFactory"]
|
swapCreatorAddr, ok := m["swapCreatorAddr"]
|
||||||
require.True(t, ok)
|
require.True(t, ok)
|
||||||
forwarderAddr, ok := m["forwarder"]
|
forwarderAddr, ok := m["forwarderAddr"]
|
||||||
require.True(t, ok)
|
require.True(t, ok)
|
||||||
|
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
ecCtx := context.Background()
|
ecCtx := context.Background()
|
||||||
discoveredForwarderAddr, err :=
|
discoveredForwarderAddr, err :=
|
||||||
contracts.CheckSwapFactoryContractCode(ecCtx, ec, ethcommon.HexToAddress(swapFactoryAddr))
|
contracts.CheckSwapCreatorContractCode(ecCtx, ec, ethcommon.HexToAddress(swapCreatorAddr))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, strings.ToLower(discoveredForwarderAddr.Hex()), forwarderAddr)
|
require.Equal(t, strings.ToLower(discoveredForwarderAddr.Hex()), forwarderAddr)
|
||||||
|
|
||||||
// something is seriously wrong if this next check fails, as CheckSwapFactoryContractCode
|
// something is seriously wrong if this next check fails, as CheckSwapCreatorContractCode
|
||||||
// should have already validated the forwarder bytecode
|
// should have already validated the forwarder bytecode
|
||||||
err = contracts.CheckForwarderContractCode(ecCtx, ec, ethcommon.HexToAddress(forwarderAddr))
|
err = contracts.CheckForwarderContractCode(ecCtx, ec, ethcommon.HexToAddress(forwarderAddr))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -120,7 +120,7 @@ func TestDaemon_DevXMRMaker(t *testing.T) {
|
|||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
|
|
||||||
// We tested --deploy with the taker, so test passing the contract address here
|
// We tested --deploy with the taker, so test passing the contract address here
|
||||||
swapFactoryAddr, _, err := deploySwapFactory(context.Background(), ec, key, ethcommon.Address{}, t.TempDir())
|
swapCreatorAddr, _, err := deploySwapCreator(context.Background(), ec, key, ethcommon.Address{}, t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
flags := []string{
|
flags := []string{
|
||||||
@@ -128,7 +128,7 @@ func TestDaemon_DevXMRMaker(t *testing.T) {
|
|||||||
fmt.Sprintf("--%s", flagDevXMRMaker),
|
fmt.Sprintf("--%s", flagDevXMRMaker),
|
||||||
fmt.Sprintf("--%s=dev", flagEnv),
|
fmt.Sprintf("--%s=dev", flagEnv),
|
||||||
fmt.Sprintf("--%s=debug", flagLogLevel),
|
fmt.Sprintf("--%s=debug", flagLogLevel),
|
||||||
fmt.Sprintf("--%s=%s", flagContractAddress, swapFactoryAddr),
|
fmt.Sprintf("--%s=%s", flagContractAddress, swapCreatorAddr),
|
||||||
fmt.Sprintf("--%s=%s", flagDataDir, t.TempDir()),
|
fmt.Sprintf("--%s=%s", flagDataDir, t.TempDir()),
|
||||||
fmt.Sprintf("--%s=%d", flagRPCPort, rpcPort),
|
fmt.Sprintf("--%s=%d", flagRPCPort, rpcPort),
|
||||||
fmt.Sprintf("--%s=0", flagLibp2pPort),
|
fmt.Sprintf("--%s=0", flagLibp2pPort),
|
||||||
@@ -157,9 +157,9 @@ func TestDaemon_BadFlags(t *testing.T) {
|
|||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
ctx, _ := newTestContext(t)
|
ctx, _ := newTestContext(t)
|
||||||
|
|
||||||
swapFactoryAddr, swapFactory, err := deploySwapFactory(ctx, ec, key, ethcommon.Address{}, t.TempDir())
|
swapCreatorAddr, swapCreator, err := deploySwapCreator(ctx, ec, key, ethcommon.Address{}, t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
forwarderAddr, err := swapFactory.TrustedForwarder(nil)
|
forwarderAddr, err := swapCreator.TrustedForwarder(nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
baseFlags := []string{
|
baseFlags := []string{
|
||||||
@@ -184,10 +184,10 @@ func TestDaemon_BadFlags(t *testing.T) {
|
|||||||
expectErr: `flag "deploy" or "contract-address" is required for env=dev`,
|
expectErr: `flag "deploy" or "contract-address" is required for env=dev`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
description: "deploy SwapFactory with invalid forwarder",
|
description: "deploy SwapCreator with invalid forwarder",
|
||||||
extraFlags: []string{
|
extraFlags: []string{
|
||||||
fmt.Sprintf("--%s", flagDeploy),
|
fmt.Sprintf("--%s", flagDeploy),
|
||||||
fmt.Sprintf("--%s=%s", flagForwarderAddress, swapFactoryAddr), // passing wrong contract
|
fmt.Sprintf("--%s=%s", flagForwarderAddress, swapCreatorAddr), // passing wrong contract
|
||||||
},
|
},
|
||||||
expectErr: "does not contain correct Forwarder code",
|
expectErr: "does not contain correct Forwarder code",
|
||||||
},
|
},
|
||||||
@@ -204,19 +204,19 @@ func TestDaemon_BadFlags(t *testing.T) {
|
|||||||
extraFlags: []string{
|
extraFlags: []string{
|
||||||
fmt.Sprintf("--%s=%s", flagForwarderAddress, forwarderAddr),
|
fmt.Sprintf("--%s=%s", flagForwarderAddress, forwarderAddr),
|
||||||
// next flag is needed, or we fail on a different error first
|
// next flag is needed, or we fail on a different error first
|
||||||
fmt.Sprintf("--%s=%s", flagContractAddress, swapFactoryAddr),
|
fmt.Sprintf("--%s=%s", flagContractAddress, swapCreatorAddr),
|
||||||
},
|
},
|
||||||
expectErr: fmt.Sprintf(`using flag "%s" requires the "%s" flag`, flagForwarderAddress, flagDeploy),
|
expectErr: fmt.Sprintf(`using flag "%s" requires the "%s" flag`, flagForwarderAddress, flagDeploy),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
description: "pass invalid SwapFactory contract",
|
description: "pass invalid SwapCreator contract",
|
||||||
extraFlags: []string{
|
extraFlags: []string{
|
||||||
fmt.Sprintf("--%s=%s", flagContractAddress, forwarderAddr), // passing wrong contract
|
fmt.Sprintf("--%s=%s", flagContractAddress, forwarderAddr), // passing wrong contract
|
||||||
},
|
},
|
||||||
expectErr: "does not contain correct SwapFactory code",
|
expectErr: "does not contain correct SwapCreator code",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
description: "pass SwapFactory contract an invalid address (wrong length)",
|
description: "pass SwapCreator contract an invalid address (wrong length)",
|
||||||
extraFlags: []string{
|
extraFlags: []string{
|
||||||
fmt.Sprintf("--%s=%s", flagContractAddress, "0xFFFF"), // too short
|
fmt.Sprintf("--%s=%s", flagContractAddress, "0xFFFF"), // too short
|
||||||
},
|
},
|
||||||
@@ -226,7 +226,7 @@ func TestDaemon_BadFlags(t *testing.T) {
|
|||||||
// this one also happens when people accidentally confuse swapd with swapcli
|
// this one also happens when people accidentally confuse swapd with swapcli
|
||||||
description: "forgot to prefix the flag name with dashes",
|
description: "forgot to prefix the flag name with dashes",
|
||||||
extraFlags: []string{
|
extraFlags: []string{
|
||||||
flagContractAddress, swapFactoryAddr.String(),
|
flagContractAddress, swapCreatorAddr.String(),
|
||||||
},
|
},
|
||||||
expectErr: fmt.Sprintf("unknown command %q", flagContractAddress),
|
expectErr: fmt.Sprintf("unknown command %q", flagContractAddress),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ coverage:
|
|||||||
# Don't calculate code coverage percentages on generated abigen files
|
# Don't calculate code coverage percentages on generated abigen files
|
||||||
# or our profiling code
|
# or our profiling code
|
||||||
ignore:
|
ignore:
|
||||||
- ethereum/swap_factory.go
|
- ethereum/swap_creator.go
|
||||||
- ethereum/aggregator_v3_interface.go
|
- ethereum/aggregator_v3_interface.go
|
||||||
- ethereum/erc20_mock.go
|
- ethereum/erc20_mock.go
|
||||||
- ethereum/ierc20.go
|
- ethereum/ierc20.go
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ type MoneroNode struct {
|
|||||||
|
|
||||||
// Config contains constants that are defaults for various environments
|
// Config contains constants that are defaults for various environments
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Env Environment
|
Env Environment
|
||||||
DataDir string
|
DataDir string
|
||||||
MoneroNodes []*MoneroNode
|
MoneroNodes []*MoneroNode
|
||||||
SwapFactoryAddress ethcommon.Address
|
SwapCreatorAddr ethcommon.Address
|
||||||
ForwarderContractAddress ethcommon.Address
|
ForwarderAddr ethcommon.Address
|
||||||
Bootnodes []string
|
Bootnodes []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// MainnetConfig is the mainnet ethereum and monero configuration
|
// MainnetConfig is the mainnet ethereum and monero configuration
|
||||||
@@ -86,8 +86,8 @@ func StagenetConfig() *Config {
|
|||||||
Port: 38081,
|
Port: 38081,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
SwapFactoryAddress: ethcommon.HexToAddress("0x531BAAceB7939C04ef0DE517557a2f84F5545EFB"),
|
SwapCreatorAddr: ethcommon.HexToAddress("0x2C3b31E4379ab5B1B0Cb12B37D2B268FEf44d7f0"),
|
||||||
ForwarderContractAddress: ethcommon.HexToAddress("0x8730e444bB1501C23BC3E170405a8EbAFD138000"),
|
ForwarderAddr: ethcommon.HexToAddress("0xF45e206B38f5901daBf9758fcC2CFce6aEe5B134"),
|
||||||
Bootnodes: []string{
|
Bootnodes: []string{
|
||||||
"/ip4/134.122.115.208/tcp/9900/p2p/12D3KooWDqCzbjexHEa8Rut7bzxHFpRMZyDRW1L6TGkL1KY24JH5",
|
"/ip4/134.122.115.208/tcp/9900/p2p/12D3KooWDqCzbjexHEa8Rut7bzxHFpRMZyDRW1L6TGkL1KY24JH5",
|
||||||
"/ip4/143.198.123.27/tcp/9900/p2p/12D3KooWSc4yFkPWBFmPToTMbhChH3FAgGH96DNzSg5fio1pQYoN",
|
"/ip4/143.198.123.27/tcp/9900/p2p/12D3KooWSc4yFkPWBFmPToTMbhChH3FAgGH96DNzSg5fio1pQYoN",
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ const (
|
|||||||
TimeFmtNSecs = "2006-01-02-15:04:05.999999999"
|
TimeFmtNSecs = "2006-01-02-15:04:05.999999999"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SwapFactory.sol event signatures
|
// SwapCreator.sol event signatures
|
||||||
const (
|
const (
|
||||||
ReadyEventSignature = "Ready(bytes32)"
|
ReadyEventSignature = "Ready(bytes32)"
|
||||||
ClaimedEventSignature = "Claimed(bytes32,bytes32)"
|
ClaimedEventSignature = "Claimed(bytes32,bytes32)"
|
||||||
|
|||||||
@@ -54,8 +54,8 @@ func RunSwapDaemon(ctx context.Context, conf *SwapdConfig) (err error) {
|
|||||||
conf.Libp2pKeyfile = path.Join(conf.EnvConf.DataDir, common.DefaultLibp2pKeyFileName)
|
conf.Libp2pKeyfile = path.Join(conf.EnvConf.DataDir, common.DefaultLibp2pKeyFileName)
|
||||||
}
|
}
|
||||||
|
|
||||||
if conf.EnvConf.SwapFactoryAddress == (ethcommon.Address{}) {
|
if conf.EnvConf.SwapCreatorAddr == (ethcommon.Address{}) {
|
||||||
panic("swap factory address not specified")
|
panic("swap creator address not specified")
|
||||||
}
|
}
|
||||||
|
|
||||||
ec := conf.EthereumClient
|
ec := conf.EthereumClient
|
||||||
@@ -105,14 +105,14 @@ func RunSwapDaemon(ctx context.Context, conf *SwapdConfig) (err error) {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
swapBackend, err := backend.NewBackend(&backend.Config{
|
swapBackend, err := backend.NewBackend(&backend.Config{
|
||||||
Ctx: ctx,
|
Ctx: ctx,
|
||||||
MoneroClient: conf.MoneroClient,
|
MoneroClient: conf.MoneroClient,
|
||||||
EthereumClient: conf.EthereumClient,
|
EthereumClient: conf.EthereumClient,
|
||||||
Environment: conf.EnvConf.Env,
|
Environment: conf.EnvConf.Env,
|
||||||
SwapFactoryAddress: conf.EnvConf.SwapFactoryAddress,
|
SwapCreatorAddr: conf.EnvConf.SwapCreatorAddr,
|
||||||
SwapManager: sm,
|
SwapManager: sm,
|
||||||
RecoveryDB: sdb.RecoveryDB(),
|
RecoveryDB: sdb.RecoveryDB(),
|
||||||
Net: host,
|
Net: host,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to make backend: %w", err)
|
return fmt.Errorf("failed to make backend: %w", err)
|
||||||
|
|||||||
@@ -62,11 +62,11 @@ func init() {
|
|||||||
_ = logging.SetLogLevel("xmrtaker", level)
|
_ = logging.SetLogLevel("xmrtaker", level)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _swapFactoryAddress *ethcommon.Address
|
var _swapCreatorAddr *ethcommon.Address
|
||||||
|
|
||||||
func getSwapFactoryAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address {
|
func getSwapCreatorAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address {
|
||||||
if _swapFactoryAddress != nil {
|
if _swapCreatorAddr != nil {
|
||||||
return *_swapFactoryAddress
|
return *_swapCreatorAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -75,11 +75,11 @@ func getSwapFactoryAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address
|
|||||||
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, ethKey)
|
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, ethKey)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
swapFactoryAddr, _, err := contracts.DeploySwapFactoryWithKey(ctx, ec, ethKey, forwarderAddr)
|
swapCreatorAddr, _, err := contracts.DeploySwapCreatorWithKey(ctx, ec, ethKey, forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
_swapFactoryAddress = &swapFactoryAddr
|
_swapCreatorAddr = &swapCreatorAddr
|
||||||
return swapFactoryAddr
|
return swapCreatorAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
func privKeyToAddr(privKey *ecdsa.PrivateKey) ethcommon.Address {
|
func privKeyToAddr(privKey *ecdsa.PrivateKey) ethcommon.Address {
|
||||||
@@ -161,7 +161,7 @@ func createTestConf(t *testing.T, ethKey *ecdsa.PrivateKey) *SwapdConfig {
|
|||||||
envConf := new(common.Config)
|
envConf := new(common.Config)
|
||||||
*envConf = *common.ConfigDefaultsForEnv(common.Development)
|
*envConf = *common.ConfigDefaultsForEnv(common.Development)
|
||||||
envConf.DataDir = t.TempDir()
|
envConf.DataDir = t.TempDir()
|
||||||
envConf.SwapFactoryAddress = getSwapFactoryAddress(t, ec.Raw())
|
envConf.SwapCreatorAddr = getSwapCreatorAddress(t, ec.Raw())
|
||||||
|
|
||||||
return &SwapdConfig{
|
return &SwapdConfig{
|
||||||
EnvConf: envConf,
|
EnvConf: envConf,
|
||||||
@@ -227,7 +227,7 @@ func TestRunSwapDaemon_SwapBobHasNoEth_AliceRelaysClaim(t *testing.T) {
|
|||||||
|
|
||||||
aliceConf := createTestConf(t, tests.GetTakerTestKey(t))
|
aliceConf := createTestConf(t, tests.GetTakerTestKey(t))
|
||||||
|
|
||||||
timeout := 5 * time.Minute
|
timeout := 7 * time.Minute
|
||||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
||||||
|
|
||||||
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
||||||
@@ -320,7 +320,7 @@ func TestRunSwapDaemon_NoRelayersAvailable_Refund(t *testing.T) {
|
|||||||
aliceConf := createTestConf(t, aliceEthKey)
|
aliceConf := createTestConf(t, aliceEthKey)
|
||||||
minimumFundAlice(t, aliceConf.EthereumClient, providesAmt)
|
minimumFundAlice(t, aliceConf.EthereumClient, providesAmt)
|
||||||
|
|
||||||
timeout := 7 * time.Minute
|
timeout := 8 * time.Minute
|
||||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
||||||
|
|
||||||
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
||||||
@@ -405,7 +405,7 @@ func TestRunSwapDaemon_CharlieRelays(t *testing.T) {
|
|||||||
charlieStartBal, err := charlieConf.EthereumClient.Balance(context.Background())
|
charlieStartBal, err := charlieConf.EthereumClient.Balance(context.Background())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
timeout := 5 * time.Minute
|
timeout := 7 * time.Minute
|
||||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
||||||
|
|
||||||
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
||||||
@@ -510,7 +510,7 @@ func TestRunSwapDaemon_CharlieIsBroke_AliceRelays(t *testing.T) {
|
|||||||
charlieConf := createTestConf(t, charlieEthKey)
|
charlieConf := createTestConf(t, charlieEthKey)
|
||||||
charlieConf.IsRelayer = true
|
charlieConf.IsRelayer = true
|
||||||
|
|
||||||
timeout := 5 * time.Minute
|
timeout := 7 * time.Minute
|
||||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
||||||
|
|
||||||
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
bc, err := wsclient.NewWsClient(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", bobConf.RPCPort))
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ func (db *RecoveryDB) GetSwapRelayerInfo(id types.Hash) (*types.OfferExtra, erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PutContractSwapInfo stores the given contract swap ID (which is not the same as the daemon
|
// PutContractSwapInfo stores the given contract swap ID (which is not the same as the daemon
|
||||||
// swap ID, but is instead a hash of the `SwapFactorySwap` structure)
|
// swap ID, but is instead a hash of the `SwapCreatorSwap` structure)
|
||||||
// and contract swap structure for the given swap ID.
|
// and contract swap structure for the given swap ID.
|
||||||
func (db *RecoveryDB) PutContractSwapInfo(id types.Hash, info *EthereumSwapInfo) error {
|
func (db *RecoveryDB) PutContractSwapInfo(id types.Hash, info *EthereumSwapInfo) error {
|
||||||
val, err := vjson.MarshalStruct(info)
|
val, err := vjson.MarshalStruct(info)
|
||||||
@@ -91,7 +91,7 @@ func (db *RecoveryDB) PutContractSwapInfo(id types.Hash, info *EthereumSwapInfo)
|
|||||||
return db.db.Flush()
|
return db.db.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContractSwapInfo returns the contract swap ID (a hash of the `SwapFactorySwap` structure) and
|
// GetContractSwapInfo returns the contract swap ID (a hash of the `SwapCreatorSwap` structure) and
|
||||||
// and contract swap structure for the given swap ID.
|
// and contract swap structure for the given swap ID.
|
||||||
func (db *RecoveryDB) GetContractSwapInfo(id types.Hash) (*EthereumSwapInfo, error) {
|
func (db *RecoveryDB) GetContractSwapInfo(id types.Hash) (*EthereumSwapInfo, error) {
|
||||||
key := getRecoveryDBKey(id, contractSwapInfoPrefix)
|
key := getRecoveryDBKey(id, contractSwapInfoPrefix)
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
|||||||
si := &EthereumSwapInfo{
|
si := &EthereumSwapInfo{
|
||||||
StartNumber: big.NewInt(12345),
|
StartNumber: big.NewInt(12345),
|
||||||
SwapID: types.Hash{1, 2, 3, 4},
|
SwapID: types.Hash{1, 2, 3, 4},
|
||||||
Swap: &contracts.SwapFactorySwap{
|
Swap: &contracts.SwapCreatorSwap{
|
||||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||||
@@ -48,7 +48,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
|||||||
Value: big.NewInt(9876),
|
Value: big.NewInt(9876),
|
||||||
Nonce: big.NewInt(1234),
|
Nonce: big.NewInt(1234),
|
||||||
},
|
},
|
||||||
ContractAddress: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
SwapCreatorAddr: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStr := `{
|
expectedStr := `{
|
||||||
@@ -65,7 +65,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
|||||||
"value": 9876,
|
"value": 9876,
|
||||||
"nonce": 1234
|
"nonce": 1234
|
||||||
},
|
},
|
||||||
"contractAddress": "0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"
|
"swapCreatorAddr": "0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"
|
||||||
}`
|
}`
|
||||||
jsonData, err := vjson.MarshalStruct(si)
|
jsonData, err := vjson.MarshalStruct(si)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -151,7 +151,7 @@ func TestRecoveryDB_DeleteSwap(t *testing.T) {
|
|||||||
si := &EthereumSwapInfo{
|
si := &EthereumSwapInfo{
|
||||||
StartNumber: big.NewInt(12345),
|
StartNumber: big.NewInt(12345),
|
||||||
SwapID: types.Hash{1, 2, 3, 4},
|
SwapID: types.Hash{1, 2, 3, 4},
|
||||||
Swap: &contracts.SwapFactorySwap{
|
Swap: &contracts.SwapCreatorSwap{
|
||||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||||
@@ -162,7 +162,7 @@ func TestRecoveryDB_DeleteSwap(t *testing.T) {
|
|||||||
Value: big.NewInt(9876),
|
Value: big.NewInt(9876),
|
||||||
Nonce: big.NewInt(1234),
|
Nonce: big.NewInt(1234),
|
||||||
},
|
},
|
||||||
ContractAddress: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
SwapCreatorAddr: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||||
}
|
}
|
||||||
|
|
||||||
info := &types.OfferExtra{
|
info := &types.OfferExtra{
|
||||||
|
|||||||
10
db/types.go
10
db/types.go
@@ -20,12 +20,12 @@ type EthereumSwapInfo struct {
|
|||||||
|
|
||||||
// SwapID is the swap ID used by the swap contract; not the same as the
|
// SwapID is the swap ID used by the swap contract; not the same as the
|
||||||
// swap/offer ID used by swapd. It's the hash of the ABI encoded
|
// swap/offer ID used by swapd. It's the hash of the ABI encoded
|
||||||
// `contracts.SwapFactorySwap` struct.
|
// `contracts.SwapCreatorSwap` struct.
|
||||||
SwapID types.Hash `json:"swapID" validate:"required"`
|
SwapID types.Hash `json:"swapID" validate:"required"`
|
||||||
|
|
||||||
// Swap is the `Swap` structure inside SwapFactory.sol.
|
// Swap is the `Swap` structure inside SwapCreator.sol.
|
||||||
Swap *contracts.SwapFactorySwap `json:"swap" validate:"required"`
|
Swap *contracts.SwapCreatorSwap `json:"swap" validate:"required"`
|
||||||
|
|
||||||
// ContractAddress is the address of the contract on which the swap was created.
|
// SwapCreatorAddr is the address of the contract on which the swap was created.
|
||||||
ContractAddress ethcommon.Address `json:"contractAddress" validate:"required"`
|
SwapCreatorAddr ethcommon.Address `json:"swapCreatorAddr" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,19 +12,28 @@ You can use the script `scripts/setup-env.sh` to quickly set up local monerod-te
|
|||||||
ganache instances. If you need to later kill `ganache`, `monerod`, `monero-wallet-rpc`, or
|
ganache instances. If you need to later kill `ganache`, `monerod`, `monero-wallet-rpc`, or
|
||||||
`swapd` instances, you can use `scripts/cleanup-test-processes.sh`.
|
`swapd` instances, you can use `scripts/cleanup-test-processes.sh`.
|
||||||
|
|
||||||
## Deploying or using deployed SwapFactory.sol
|
## Deploying or using deployed SwapCreator.sol
|
||||||
|
|
||||||
The swap program uses a "factory" contract for the Ethereum side to reduce gas costs from deploying a new contract for each swap. The contract can be found in [here](../ethereum/contracts/SwapFactory.sol). For each new swap, the eth-holding party will call `NewSwap` on the factory contract, initiating a swap instance inside the contract.
|
The swap program uses a "creator" contract for the Ethereum side to reduce gas
|
||||||
|
costs from deploying a new contract for each swap. The contract can be found in
|
||||||
|
[here](../ethereum/contracts/SwapCreator.sol). For each new swap, the
|
||||||
|
eth-holding party will call `NewSwap` on the creator contract, initiating a swap
|
||||||
|
instance inside the contract.
|
||||||
|
|
||||||
If you're developing on a local network, running a `swapd` instance with the `--dev-xmrtaker` flag will automatically deploy an instance of `SwapFactory.sol` for you. You should see the following log shortly after starting `./swapd --dev-xmrtaker`:
|
If you're developing on a local network, running a `swapd` instance with the
|
||||||
|
`--dev-xmrtaker` flag will automatically deploy an instance of `SwapCreator.sol`
|
||||||
|
for you. You should see the following log shortly after starting
|
||||||
|
`./swapd --dev-xmrtaker`:
|
||||||
```bash
|
```bash
|
||||||
# 2022-01-26T18:39:04.600-0500 INFO cmd daemon/contract.go:35 deployed SwapFactory.sol: address=0x3F2aF34E4250de94242Ac2B8A38550fd4503696d tx hash=0x638caf280178b3cfe06854b8a76a4ce355d38c5d81187836f0733cad1287b657
|
# 2022-01-26T18:39:04.600-0500 INFO cmd daemon/contract.go:35 deployed SwapCreator.sol: address=0x3F2aF34E4250de94242Ac2B8A38550fd4503696d tx hash=0x638caf280178b3cfe06854b8a76a4ce355d38c5d81187836f0733cad1287b657
|
||||||
```
|
```
|
||||||
|
|
||||||
If you wish to use an instance of `SwapFactory.sol` that's already deployed on-chain, you can use the `--contract-address` flag to specify the address. For example:
|
If you wish to use an instance of `SwapCreator.sol` that's already deployed
|
||||||
|
on-chain, you can use the `--contract-address` flag to specify the address. For
|
||||||
|
example:
|
||||||
```bash
|
```bash
|
||||||
$ ./swapd --dev-xmrtaker --contract-address 0x3F2aF34E4250de94242Ac2B8A38550fd4503696d
|
$ ./swapd --dev-xmrtaker --contract-address 0x3F2aF34E4250de94242Ac2B8A38550fd4503696d
|
||||||
# 2022-01-26T18:56:31.627-0500 INFO cmd daemon/contract.go:42 loaded SwapFactory.sol from address 0x3F2aF34E4250de94242Ac2B8A38550fd4503696d
|
# 2022-01-26T18:56:31.627-0500 INFO cmd daemon/contract.go:42 loaded SwapCreator.sol from address 0x3F2aF34E4250de94242Ac2B8A38550fd4503696d
|
||||||
```
|
```
|
||||||
|
|
||||||
## Compiling contract bindings
|
## Compiling contract bindings
|
||||||
@@ -33,7 +42,7 @@ If you update the `Swap.sol` contract for some reason, you will need to re-gener
|
|||||||
for the contract. **Note:** you do *not* need to do this to try out the swap; only if you want to
|
for the contract. **Note:** you do *not* need to do this to try out the swap; only if you want to
|
||||||
edit the contract for development purposes.
|
edit the contract for development purposes.
|
||||||
|
|
||||||
Download solc v0.8.17: https://github.com/ethereum/solidity/releases/tag/v0.8.17
|
Download solc v0.8.19: https://github.com/ethereum/solidity/releases/tag/v0.8.19
|
||||||
|
|
||||||
If `solc` with the needed version is not in your path (or not first in your path), set the
|
If `solc` with the needed version is not in your path (or not first in your path), set the
|
||||||
`SOLC_BIN` environment variable to the correct version:
|
`SOLC_BIN` environment variable to the correct version:
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ Now get the ethereum contract address that Alice deployed to. This can be pulled
|
|||||||
the file ..., or if you have `jq` installed (available via `sudo apt install jq`), you can set a
|
the file ..., or if you have `jq` installed (available via `sudo apt install jq`), you can set a
|
||||||
variable like this:
|
variable like this:
|
||||||
```bash
|
```bash
|
||||||
CONTRACT_ADDR=$(jq -r .swapFactory "${TMPDIR-/tmp}"/xmrtaker-*/contract-addresses.json)
|
CONTRACT_ADDR=$(jq -r .swapCreatorAddr "${TMPDIR-/tmp}"/xmrtaker-*/contract-addresses.json)
|
||||||
```
|
```
|
||||||
|
|
||||||
Now start Bob's swapd instance:
|
Now start Bob's swapd instance:
|
||||||
@@ -220,4 +220,4 @@ To query information for a past swap using its ID, you can run:
|
|||||||
./bin/swapcli past --offer-id <id>
|
./bin/swapcli past --offer-id <id>
|
||||||
```
|
```
|
||||||
|
|
||||||
For both of these commands, if no `--offer-id` is passed, all ongoing or past swaps will be returned.
|
For both of these commands, if no `--offer-id` is passed, all ongoing or past swaps will be returned.
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ You can also try the swap on another Ethereum or EVM-compatible testnet. However
|
|||||||
|
|
||||||
To connect to a different Ethereum network, follow [Setup](#setup) steps 4-7 but with your desired network. Then, start `swapd` with your specified private key file, endpoint, and chain ID. Common chain IDs can be found [here](https://besu.hyperledger.org/en/stable/Concepts/NetworkID-And-ChainID/).
|
To connect to a different Ethereum network, follow [Setup](#setup) steps 4-7 but with your desired network. Then, start `swapd` with your specified private key file, endpoint, and chain ID. Common chain IDs can be found [here](https://besu.hyperledger.org/en/stable/Concepts/NetworkID-And-ChainID/).
|
||||||
|
|
||||||
> Note: The `--deploy` flag to `swapd` creates a new instance of `SwapFactory.sol` to the
|
> Note: The `--deploy` flag to `swapd` creates a new instance of `SwapCreator.sol` to the
|
||||||
network. You need to have funds in your account to deploy the contract. To use a contract
|
network. You need to have funds in your account to deploy the contract. To use a contract
|
||||||
deployed with `--deploy` in subsequent `swapd` instances, use the flag
|
deployed with `--deploy` in subsequent `swapd` instances, use the flag
|
||||||
`--contract-addr=ADDRESS`. When using `stagenet`, a deployed contract already exists and
|
`--contract-addr=ADDRESS`. When using `stagenet`, a deployed contract already exists and
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
// Copyright 2023 Athanor Labs (ON)
|
|
||||||
// SPDX-License-Identifier: LGPL-3.0-only
|
|
||||||
|
|
||||||
// Code generated - DO NOT EDIT.
|
// Code generated - DO NOT EDIT.
|
||||||
// This file is a generated binding and any manual changes will be lost.
|
// This file is a generated binding and any manual changes will be lost.
|
||||||
|
|
||||||
@@ -29,6 +26,7 @@ var (
|
|||||||
_ = common.Big1
|
_ = common.Big1
|
||||||
_ = types.BloomLookup
|
_ = types.BloomLookup
|
||||||
_ = event.NewSubscription
|
_ = event.NewSubscription
|
||||||
|
_ = abi.ConvertType
|
||||||
)
|
)
|
||||||
|
|
||||||
// AggregatorV3InterfaceMetaData contains all meta data concerning the AggregatorV3Interface contract.
|
// AggregatorV3InterfaceMetaData contains all meta data concerning the AggregatorV3Interface contract.
|
||||||
@@ -137,11 +135,11 @@ func NewAggregatorV3InterfaceFilterer(address common.Address, filterer bind.Cont
|
|||||||
|
|
||||||
// bindAggregatorV3Interface binds a generic wrapper to an already deployed contract.
|
// bindAggregatorV3Interface binds a generic wrapper to an already deployed contract.
|
||||||
func bindAggregatorV3Interface(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
func bindAggregatorV3Interface(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
||||||
parsed, err := abi.JSON(strings.NewReader(AggregatorV3InterfaceABI))
|
parsed, err := AggregatorV3InterfaceMetaData.GetAbi()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
|
return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call invokes the (constant) contract method with params as input values and
|
// Call invokes the (constant) contract method with params as input values and
|
||||||
|
|||||||
2
ethereum/block/testdata/generate-bindings.sh
vendored
2
ethereum/block/testdata/generate-bindings.sh
vendored
@@ -14,7 +14,7 @@ fi
|
|||||||
"${SOLC_BIN}" --abi UTContract.sol -o . --overwrite
|
"${SOLC_BIN}" --abi UTContract.sol -o . --overwrite
|
||||||
"${SOLC_BIN}" --bin UTContract.sol -o . --overwrite
|
"${SOLC_BIN}" --bin UTContract.sol -o . --overwrite
|
||||||
|
|
||||||
# Use abigen 1.10.17-stable to match how we compile the SwapFactory contract
|
# Use abigen 1.10.17-stable to match how we compile the SwapCreator contract
|
||||||
"${ABIGEN}" --abi UTContract.abi --bin UTContract.bin --pkg block --type UTContract --out ../ut_contract_test.go
|
"${ABIGEN}" --abi UTContract.abi --bin UTContract.bin --pkg block --type UTContract --out ../ut_contract_test.go
|
||||||
|
|
||||||
rm -f UTContract.abi UTContract.bin
|
rm -f UTContract.abi UTContract.bin
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
// Copyright 2023 Athanor Labs (ON)
|
|
||||||
// SPDX-License-Identifier: LGPL-3.0-only
|
|
||||||
|
|
||||||
// Code generated - DO NOT EDIT.
|
// Code generated - DO NOT EDIT.
|
||||||
// This file is a generated binding and any manual changes will be lost.
|
// This file is a generated binding and any manual changes will be lost.
|
||||||
|
|
||||||
@@ -29,12 +26,13 @@ var (
|
|||||||
_ = common.Big1
|
_ = common.Big1
|
||||||
_ = types.BloomLookup
|
_ = types.BloomLookup
|
||||||
_ = event.NewSubscription
|
_ = event.NewSubscription
|
||||||
|
_ = abi.ConvertType
|
||||||
)
|
)
|
||||||
|
|
||||||
// UTContractMetaData contains all meta data concerning the UTContract contract.
|
// UTContractMetaData contains all meta data concerning the UTContract contract.
|
||||||
var UTContractMetaData = &bind.MetaData{
|
var UTContractMetaData = &bind.MetaData{
|
||||||
ABI: "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_stamp\",\"type\":\"uint256\"}],\"name\":\"checkStamp\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]",
|
ABI: "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_stamp\",\"type\":\"uint256\"}],\"name\":\"checkStamp\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]",
|
||||||
Bin: "0x608060405234801561001057600080fd5b506101da806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d5f7a03a14610030575b600080fd5b61004a600480360381019061004591906100d4565b61004c565b005b8042111561008f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161008690610184565b60405180910390fd5b8060008190555050565b600080fd5b6000819050919050565b6100b18161009e565b81146100bc57600080fd5b50565b6000813590506100ce816100a8565b92915050565b6000602082840312156100ea576100e9610099565b5b60006100f8848285016100bf565b91505092915050565b600082825260208201905092915050565b7f626c6f636b2e74696d657374616d7020776173206e6f74206c6573732074686160008201527f6e207374616d7000000000000000000000000000000000000000000000000000602082015250565b600061016e602783610101565b915061017982610112565b604082019050919050565b6000602082019050818103600083015261019d81610161565b905091905056fea26469706673582212203a38c90eb8e83a68408aca6e96e7fab891b951de030c24bcc8a3a67dbb87c7d764736f6c63430008110033",
|
Bin: "0x608060405234801561001057600080fd5b506101da806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d5f7a03a14610030575b600080fd5b61004a600480360381019061004591906100d4565b61004c565b005b8042111561008f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161008690610184565b60405180910390fd5b8060008190555050565b600080fd5b6000819050919050565b6100b18161009e565b81146100bc57600080fd5b50565b6000813590506100ce816100a8565b92915050565b6000602082840312156100ea576100e9610099565b5b60006100f8848285016100bf565b91505092915050565b600082825260208201905092915050565b7f626c6f636b2e74696d657374616d7020776173206e6f74206c6573732074686160008201527f6e207374616d7000000000000000000000000000000000000000000000000000602082015250565b600061016e602783610101565b915061017982610112565b604082019050919050565b6000602082019050818103600083015261019d81610161565b905091905056fea2646970667358221220e3debdc387582462e246390796d566e062d5965fb0bd8de5af573ad815d24b0564736f6c63430008130033",
|
||||||
}
|
}
|
||||||
|
|
||||||
// UTContractABI is the input ABI used to generate the binding from.
|
// UTContractABI is the input ABI used to generate the binding from.
|
||||||
@@ -159,11 +157,11 @@ func NewUTContractFilterer(address common.Address, filterer bind.ContractFiltere
|
|||||||
|
|
||||||
// bindUTContract binds a generic wrapper to an already deployed contract.
|
// bindUTContract binds a generic wrapper to an already deployed contract.
|
||||||
func bindUTContract(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
func bindUTContract(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
||||||
parsed, err := abi.JSON(strings.NewReader(UTContractABI))
|
parsed, err := UTContractMetaData.GetAbi()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
|
return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call invokes the (constant) contract method with params as input values and
|
// Call invokes the (constant) contract method with params as input values and
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -20,7 +20,7 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// deployContract is a test helper that deploys the SwapFactory contract and returns the
|
// deployContract is a test helper that deploys the SwapCreator contract and returns the
|
||||||
// deployed address
|
// deployed address
|
||||||
func deployContract(
|
func deployContract(
|
||||||
t *testing.T,
|
t *testing.T,
|
||||||
@@ -29,7 +29,7 @@ func deployContract(
|
|||||||
trustedForwarder ethcommon.Address,
|
trustedForwarder ethcommon.Address,
|
||||||
) ethcommon.Address {
|
) ethcommon.Address {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
contractAddr, _, err := DeploySwapFactoryWithKey(ctx, ec, pk, trustedForwarder)
|
contractAddr, _, err := DeploySwapCreatorWithKey(ctx, ec, pk, trustedForwarder)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
return contractAddr
|
return contractAddr
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ func deployForwarder(t *testing.T, ec *ethclient.Client, pk *ecdsa.PrivateKey) e
|
|||||||
return addr
|
return addr
|
||||||
}
|
}
|
||||||
|
|
||||||
// getContractCode is a test helper that deploys the swap factory contract to read back
|
// getContractCode is a test helper that deploys the swap creator contract to read back
|
||||||
// and return the finalised byte code post deployment.
|
// and return the finalised byte code post deployment.
|
||||||
func getContractCode(t *testing.T, trustedForwarder ethcommon.Address) []byte {
|
func getContractCode(t *testing.T, trustedForwarder ethcommon.Address) []byte {
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
@@ -59,20 +59,20 @@ func TestCheckForwarderContractCode(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// This test will fail if the compiled SwapFactory contract is updated, but the
|
// This test will fail if the compiled SwapCreator contract is updated, but the
|
||||||
// expectedSwapFactoryBytecodeHex constant is not updated. Use this test to update the
|
// expectedSwapCreatorBytecodeHex constant is not updated. Use this test to update the
|
||||||
// constant.
|
// constant.
|
||||||
func TestExpectedSwapFactoryBytecodeHex(t *testing.T) {
|
func TestExpectedSwapCreatorBytecodeHex(t *testing.T) {
|
||||||
allZeroTrustedForwarder := ethcommon.Address{}
|
allZeroTrustedForwarder := ethcommon.Address{}
|
||||||
codeHex := ethcommon.Bytes2Hex(getContractCode(t, allZeroTrustedForwarder))
|
codeHex := ethcommon.Bytes2Hex(getContractCode(t, allZeroTrustedForwarder))
|
||||||
require.Equal(t, expectedSwapFactoryBytecodeHex, codeHex,
|
require.Equal(t, expectedSwapCreatorBytecodeHex, codeHex,
|
||||||
"update the expectedSwapFactoryBytecodeHex constant with the actual value to fix this test")
|
"update the expectedSwapCreatorBytecodeHex constant with the actual value to fix this test")
|
||||||
}
|
}
|
||||||
|
|
||||||
// This test will fail if the compiled SwapFactory contract is updated, but the
|
// This test will fail if the compiled SwapCreator contract is updated, but the
|
||||||
// forwarderAddressIndexes slice of trusted forwarder locations is not updated. Use this
|
// forwarderAddrIndexes slice of trusted forwarder locations is not updated. Use
|
||||||
// test to update the slice.
|
// this test to update the slice.
|
||||||
func TestForwarderAddressIndexes(t *testing.T) {
|
func TestForwarderAddrIndexes(t *testing.T) {
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
pk := tests.GetMakerTestKey(t)
|
pk := tests.GetMakerTestKey(t)
|
||||||
trustedForwarder := deployForwarder(t, ec, pk)
|
trustedForwarder := deployForwarder(t, ec, pk)
|
||||||
@@ -86,65 +86,68 @@ func TestForwarderAddressIndexes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Logf("forwarderAddressIndexes: %v", addressLocations)
|
t.Logf("forwarderAddrIndexes: %v", addressLocations)
|
||||||
require.EqualValues(t, forwarderAddressIndices, addressLocations,
|
require.EqualValues(t, forwarderAddrIndices, addressLocations,
|
||||||
"update forwarderAddressIndexes with above logged indexes to fix this test")
|
"update forwarderAddrIndexes with above logged indexes to fix this test")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure that we correctly verify the SwapFactory contract when initialised with
|
// Ensure that we correctly verify the SwapCreator contract when initialised with
|
||||||
// different trusted forwarder addresses.
|
// different trusted forwarder addresses.
|
||||||
func TestCheckSwapFactoryContractCode(t *testing.T) {
|
func TestCheckSwapCreatorContractCode(t *testing.T) {
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
pk := tests.GetMakerTestKey(t)
|
pk := tests.GetMakerTestKey(t)
|
||||||
trustedForwarderAddresses := []string{
|
trustedForwarderAddrs := []string{
|
||||||
deployForwarder(t, ec, pk).Hex(),
|
deployForwarder(t, ec, pk).Hex(),
|
||||||
deployForwarder(t, ec, pk).Hex(),
|
deployForwarder(t, ec, pk).Hex(),
|
||||||
deployForwarder(t, ec, pk).Hex(),
|
deployForwarder(t, ec, pk).Hex(),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, addrHex := range trustedForwarderAddresses {
|
for _, addrHex := range trustedForwarderAddrs {
|
||||||
tfAddr := ethcommon.HexToAddress(addrHex)
|
tfAddr := ethcommon.HexToAddress(addrHex)
|
||||||
contractAddr := deployContract(t, ec, pk, tfAddr)
|
contractAddr := deployContract(t, ec, pk, tfAddr)
|
||||||
parsedTFAddr, err := CheckSwapFactoryContractCode(context.Background(), ec, contractAddr)
|
parsedTFAddr, err := CheckSwapCreatorContractCode(context.Background(), ec, contractAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, addrHex, parsedTFAddr.Hex())
|
require.Equal(t, addrHex, parsedTFAddr.Hex())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tests that we fail when the wrong contract byte code is found
|
// Tests that we fail when the wrong contract byte code is found
|
||||||
func TestCheckSwapFactoryContractCode_fail(t *testing.T) {
|
func TestCheckSwapCreatorContractCode_fail(t *testing.T) {
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
pk := tests.GetMakerTestKey(t)
|
pk := tests.GetMakerTestKey(t)
|
||||||
|
|
||||||
// Deploy a forwarder contract and then try to verify it as SwapFactory contract
|
// Deploy a forwarder contract and then try to verify it as SwapCreator contract
|
||||||
contractAddr := deployForwarder(t, ec, pk)
|
contractAddr := deployForwarder(t, ec, pk)
|
||||||
_, err := CheckSwapFactoryContractCode(context.Background(), ec, contractAddr)
|
_, err := CheckSwapCreatorContractCode(context.Background(), ec, contractAddr)
|
||||||
require.ErrorIs(t, err, errInvalidSwapContract)
|
require.ErrorIs(t, err, errInvalidSwapCreatorContract)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSepoliaContract(t *testing.T) {
|
func TestSepoliaContract(t *testing.T) {
|
||||||
// comment out the next line to test the default sepolia contract
|
// TODO: CI's ETH_SEPOLIA_ENDPOINT is giving 404 errors
|
||||||
t.Skip("requires access to non-vetted external sepolia node")
|
endpoint := "" // os.Getenv("ETH_SEPOLIA_ENDPOINT")
|
||||||
const sepoliaEndpoint = "https://rpc.sepolia.org/"
|
if endpoint == "" {
|
||||||
|
endpoint = "https://rpc.sepolia.org/"
|
||||||
|
}
|
||||||
|
|
||||||
// temporarily place a funded sepolia private key below to deploy the test contract
|
// temporarily place a funded sepolia private key below to deploy the test contract
|
||||||
const sepoliaKey = ""
|
const sepoliaKey = ""
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
ec, err := ethclient.Dial(sepoliaEndpoint)
|
ec, err := ethclient.Dial(endpoint)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer ec.Close()
|
defer ec.Close()
|
||||||
|
|
||||||
parsedTFAddr, err := CheckSwapFactoryContractCode(ctx, ec, common.StagenetConfig().SwapFactoryAddress)
|
parsedTFAddr, err := CheckSwapCreatorContractCode(ctx, ec, common.StagenetConfig().SwapCreatorAddr)
|
||||||
if errors.Is(err, errInvalidSwapContract) && sepoliaKey != "" {
|
if errors.Is(err, errInvalidSwapCreatorContract) && sepoliaKey != "" {
|
||||||
pk, err := ethcrypto.HexToECDSA(sepoliaKey) //nolint:govet // shadow declaration of err
|
pk, err := ethcrypto.HexToECDSA(sepoliaKey) //nolint:govet // shadow declaration of err
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
forwarderAddr := deployForwarder(t, ec, pk)
|
forwarderAddr := deployForwarder(t, ec, pk)
|
||||||
sfAddr, _, err := DeploySwapFactoryWithKey(context.Background(), ec, pk, forwarderAddr)
|
sfAddr, _, err := DeploySwapCreatorWithKey(context.Background(), ec, pk, forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("New Sepolia SwapFactory deployed with TrustedForwarder=%s", forwarderAddr)
|
t.Logf("New Sepolia SwapCreator deployed with TrustedForwarder=%s", forwarderAddr)
|
||||||
t.Fatalf("Update common.StagenetConfig.ContractAddress with %s", sfAddr.Hex())
|
t.Fatalf("Update common.StagenetConfig.ContractAddress with %s", sfAddr.Hex())
|
||||||
} else {
|
} else {
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("Sepolia SwapFactory deployed with TrustedForwarder=%s", parsedTFAddr.Hex())
|
t.Logf("Sepolia SwapCreator deployed with TrustedForwarder=%s", parsedTFAddr.Hex())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,7 @@ import {ERC2771Context} from "./ERC2771Context.sol";
|
|||||||
import {IERC20} from "./IERC20.sol";
|
import {IERC20} from "./IERC20.sol";
|
||||||
import {Secp256k1} from "./Secp256k1.sol";
|
import {Secp256k1} from "./Secp256k1.sol";
|
||||||
|
|
||||||
contract SwapFactory is ERC2771Context, Secp256k1 {
|
contract SwapCreator is ERC2771Context, Secp256k1 {
|
||||||
// Swap state is PENDING when the swap is first created and funded
|
// Swap state is PENDING when the swap is first created and funded
|
||||||
// Alice sets Stage to READY when she sees the funds locked on the other chain.
|
// Alice sets Stage to READY when she sees the funds locked on the other chain.
|
||||||
// this prevents Bob from withdrawing funds without locking funds on the other chain first
|
// this prevents Bob from withdrawing funds without locking funds on the other chain first
|
||||||
@@ -20,14 +20,14 @@ import (
|
|||||||
|
|
||||||
var log = logging.Logger("contracts")
|
var log = logging.Logger("contracts")
|
||||||
|
|
||||||
// DeploySwapFactoryWithKey deploys the SwapFactory contract using the passed privKey to
|
// DeploySwapCreatorWithKey deploys the SwapCreator contract using the passed privKey to
|
||||||
// pay for the gas.
|
// pay for the gas.
|
||||||
func DeploySwapFactoryWithKey(
|
func DeploySwapCreatorWithKey(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
privKey *ecdsa.PrivateKey,
|
privKey *ecdsa.PrivateKey,
|
||||||
forwarderAddr ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
) (ethcommon.Address, *SwapFactory, error) {
|
) (ethcommon.Address, *SwapCreator, error) {
|
||||||
|
|
||||||
txOpts, err := newTXOpts(ctx, ec, privKey)
|
txOpts, err := newTXOpts(ctx, ec, privKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -36,13 +36,13 @@ func DeploySwapFactoryWithKey(
|
|||||||
|
|
||||||
if (forwarderAddr != ethcommon.Address{}) {
|
if (forwarderAddr != ethcommon.Address{}) {
|
||||||
if err = registerDomainSeparatorIfNeeded(ctx, ec, privKey, forwarderAddr); err != nil {
|
if err = registerDomainSeparatorIfNeeded(ctx, ec, privKey, forwarderAddr); err != nil {
|
||||||
return ethcommon.Address{}, nil, fmt.Errorf("failed to deploy swap factory: %w", err)
|
return ethcommon.Address{}, nil, fmt.Errorf("failed to deploy swap creator: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
address, tx, sf, err := DeploySwapFactory(txOpts, ec, forwarderAddr)
|
address, tx, sf, err := DeploySwapCreator(txOpts, ec, forwarderAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ethcommon.Address{}, nil, fmt.Errorf("failed to deploy swap factory: %w", err)
|
return ethcommon.Address{}, nil, fmt.Errorf("failed to deploy swap creator: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = block.WaitForReceipt(ctx, ec, tx.Hash())
|
_, err = block.WaitForReceipt(ctx, ec, tx.Hash())
|
||||||
@@ -50,7 +50,7 @@ func DeploySwapFactoryWithKey(
|
|||||||
return ethcommon.Address{}, nil, err
|
return ethcommon.Address{}, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infof("deployed SwapFactory.sol: address=%s tx hash=%s", address, tx.Hash())
|
log.Infof("deployed SwapCreator.sol: address=%s tx hash=%s", address, tx.Hash())
|
||||||
|
|
||||||
return address, sf, nil
|
return address, sf, nil
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -15,7 +15,7 @@ import (
|
|||||||
"github.com/athanorlabs/atomic-swap/ethereum/block"
|
"github.com/athanorlabs/atomic-swap/ethereum/block"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSwapFactory_NewSwap_ERC20(t *testing.T) {
|
func TestSwapCreator_NewSwap_ERC20(t *testing.T) {
|
||||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
@@ -30,7 +30,7 @@ func TestSwapFactory_NewSwap_ERC20(t *testing.T) {
|
|||||||
testNewSwap(t, erc20Addr)
|
testNewSwap(t, erc20Addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_Claim_ERC20(t *testing.T) {
|
func TestSwapCreator_Claim_ERC20(t *testing.T) {
|
||||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
@@ -48,7 +48,7 @@ func TestSwapFactory_Claim_ERC20(t *testing.T) {
|
|||||||
testClaim(t, erc20Addr, 2, big.NewInt(99), erc20Contract)
|
testClaim(t, erc20Addr, 2, big.NewInt(99), erc20Contract)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_RefundBeforeT0_ERC20(t *testing.T) {
|
func TestSwapCreator_RefundBeforeT0_ERC20(t *testing.T) {
|
||||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
@@ -62,7 +62,7 @@ func TestSwapFactory_RefundBeforeT0_ERC20(t *testing.T) {
|
|||||||
testRefundBeforeT0(t, erc20Addr, 2)
|
testRefundBeforeT0(t, erc20Addr, 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_RefundAfterT1_ERC20(t *testing.T) {
|
func TestSwapCreator_RefundAfterT1_ERC20(t *testing.T) {
|
||||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ func (c *ethClient) Balance(ctx context.Context) (*big.Int, error) {
|
|||||||
return bal, nil
|
return bal, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SuggestedGasPrice returns the underlying eth client's suggested gas price
|
// SuggestGasPrice returns the underlying eth client's suggested gas price
|
||||||
// unless the user specified a fixed gas price to use, in which case the user
|
// unless the user specified a fixed gas price to use, in which case the user
|
||||||
// supplied value is returned.
|
// supplied value is returned.
|
||||||
func (c *ethClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
|
func (c *ethClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
// Copyright 2023 Athanor Labs (ON)
|
|
||||||
// SPDX-License-Identifier: LGPL-3.0-only
|
|
||||||
|
|
||||||
// Code generated - DO NOT EDIT.
|
// Code generated - DO NOT EDIT.
|
||||||
// This file is a generated binding and any manual changes will be lost.
|
// This file is a generated binding and any manual changes will be lost.
|
||||||
|
|
||||||
@@ -29,6 +26,7 @@ var (
|
|||||||
_ = common.Big1
|
_ = common.Big1
|
||||||
_ = types.BloomLookup
|
_ = types.BloomLookup
|
||||||
_ = event.NewSubscription
|
_ = event.NewSubscription
|
||||||
|
_ = abi.ConvertType
|
||||||
)
|
)
|
||||||
|
|
||||||
// IERC20MetaData contains all meta data concerning the IERC20 contract.
|
// IERC20MetaData contains all meta data concerning the IERC20 contract.
|
||||||
@@ -137,11 +135,11 @@ func NewIERC20Filterer(address common.Address, filterer bind.ContractFilterer) (
|
|||||||
|
|
||||||
// bindIERC20 binds a generic wrapper to an already deployed contract.
|
// bindIERC20 binds a generic wrapper to an already deployed contract.
|
||||||
func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
|
||||||
parsed, err := abi.JSON(strings.NewReader(IERC20ABI))
|
parsed, err := IERC20MetaData.GetAbi()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
|
return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call invokes the (constant) contract method with params as input values and
|
// Call invokes the (constant) contract method with params as input values and
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/athanorlabs/atomic-swap/common/vjson"
|
"github.com/athanorlabs/atomic-swap/common/vjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
// swap is the same as the auto-generated SwapFactorySwap type, but with some type
|
// swap is the same as the auto-generated SwapCreatorSwap type, but with some type
|
||||||
// adjustments and annotations for JSON marshalling.
|
// adjustments and annotations for JSON marshalling.
|
||||||
type swap struct {
|
type swap struct {
|
||||||
Owner common.Address `json:"owner" validate:"required"`
|
Owner common.Address `json:"owner" validate:"required"`
|
||||||
@@ -26,8 +26,8 @@ type swap struct {
|
|||||||
Nonce *big.Int `json:"nonce" validate:"required"`
|
Nonce *big.Int `json:"nonce" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON provides JSON marshalling for SwapFactorySwap
|
// MarshalJSON provides JSON marshalling for SwapCreatorSwap
|
||||||
func (sfs *SwapFactorySwap) MarshalJSON() ([]byte, error) {
|
func (sfs *SwapCreatorSwap) MarshalJSON() ([]byte, error) {
|
||||||
return vjson.MarshalStruct(&swap{
|
return vjson.MarshalStruct(&swap{
|
||||||
Owner: sfs.Owner,
|
Owner: sfs.Owner,
|
||||||
Claimer: sfs.Claimer,
|
Claimer: sfs.Claimer,
|
||||||
@@ -41,13 +41,13 @@ func (sfs *SwapFactorySwap) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// UnmarshalJSON provides JSON unmarshalling for SwapFactorySwap
|
// UnmarshalJSON provides JSON unmarshalling for SwapCreatorSwap
|
||||||
func (sfs *SwapFactorySwap) UnmarshalJSON(data []byte) error {
|
func (sfs *SwapCreatorSwap) UnmarshalJSON(data []byte) error {
|
||||||
s := &swap{}
|
s := &swap{}
|
||||||
if err := vjson.UnmarshalStruct(data, s); err != nil {
|
if err := vjson.UnmarshalStruct(data, s); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
*sfs = SwapFactorySwap{
|
*sfs = SwapCreatorSwap{
|
||||||
Owner: s.Owner,
|
Owner: s.Owner,
|
||||||
Claimer: s.Claimer,
|
Claimer: s.Claimer,
|
||||||
PubKeyClaim: s.PubKeyClaim,
|
PubKeyClaim: s.PubKeyClaim,
|
||||||
@@ -17,8 +17,8 @@ import (
|
|||||||
"github.com/athanorlabs/atomic-swap/common/vjson"
|
"github.com/athanorlabs/atomic-swap/common/vjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSwapFactorySwap_JSON(t *testing.T) {
|
func TestSwapCreatorSwap_JSON(t *testing.T) {
|
||||||
sf := &SwapFactorySwap{
|
sf := &SwapCreatorSwap{
|
||||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||||
@@ -44,7 +44,7 @@ func TestSwapFactorySwap_JSON(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.JSONEq(t, expectedJSON, string(jsonData))
|
require.JSONEq(t, expectedJSON, string(jsonData))
|
||||||
|
|
||||||
sf2 := &SwapFactorySwap{}
|
sf2 := &SwapCreatorSwap{}
|
||||||
err = json.Unmarshal(jsonData, sf2)
|
err = json.Unmarshal(jsonData, sf2)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.EqualValues(t, sf, sf2)
|
require.EqualValues(t, sf, sf2)
|
||||||
@@ -52,8 +52,8 @@ func TestSwapFactorySwap_JSON(t *testing.T) {
|
|||||||
|
|
||||||
// Ensure that our serializable swap type has the same number of fields as the original
|
// Ensure that our serializable swap type has the same number of fields as the original
|
||||||
// generated type.
|
// generated type.
|
||||||
func TestSwapFactorySwap_JSON_fieldCountEqual(t *testing.T) {
|
func TestSwapCreatorSwap_JSON_fieldCountEqual(t *testing.T) {
|
||||||
numSwapFields := reflect.TypeOf(swap{}).NumField()
|
numSwapFields := reflect.TypeOf(swap{}).NumField()
|
||||||
numSwapFactorySwapFields := reflect.TypeOf(SwapFactorySwap{}).NumField()
|
numSwapCreatorSwapFields := reflect.TypeOf(SwapCreatorSwap{}).NumField()
|
||||||
require.Equal(t, numSwapFactorySwapFields, numSwapFields)
|
require.Equal(t, numSwapCreatorSwapFields, numSwapFields)
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ func setupXMRTakerAuth(t *testing.T) (*bind.TransactOpts, *ethclient.Client, *ec
|
|||||||
|
|
||||||
func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
||||||
auth, conn, _ := setupXMRTakerAuth(t)
|
auth, conn, _ := setupXMRTakerAuth(t)
|
||||||
address, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
address, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NotEqual(t, ethcommon.Address{}, address)
|
require.NotEqual(t, ethcommon.Address{}, address)
|
||||||
require.NotNil(t, tx)
|
require.NotNil(t, tx)
|
||||||
@@ -52,7 +52,7 @@ func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
|||||||
|
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
owner := auth.From
|
owner := auth.From
|
||||||
claimer := common.EthereumPrivateKeyToAddress(tests.GetMakerTestKey(t))
|
claimer := common.EthereumPrivateKeyToAddress(tests.GetMakerTestKey(t))
|
||||||
@@ -106,7 +106,7 @@ func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// validate that off-chain swapID calculation matches the on-chain value
|
// validate that off-chain swapID calculation matches the on-chain value
|
||||||
swap := SwapFactorySwap{
|
swap := SwapCreatorSwap{
|
||||||
Owner: owner,
|
Owner: owner,
|
||||||
Claimer: claimer,
|
Claimer: claimer,
|
||||||
PubKeyClaim: pubKeyClaim,
|
PubKeyClaim: pubKeyClaim,
|
||||||
@@ -122,11 +122,11 @@ func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
|||||||
require.Equal(t, types.Hash(swapID).Hex(), swap.SwapID().Hex())
|
require.Equal(t, types.Hash(swapID).Hex(), swap.SwapID().Hex())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_NewSwap(t *testing.T) {
|
func TestSwapCreator_NewSwap(t *testing.T) {
|
||||||
testNewSwap(t, ethAssetAddress)
|
testNewSwap(t, ethAssetAddress)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_Claim_vec(t *testing.T) {
|
func TestSwapCreator_Claim_vec(t *testing.T) {
|
||||||
secret, err := hex.DecodeString("D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759")
|
secret, err := hex.DecodeString("D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
pubX, err := hex.DecodeString("3AF1E1EFA4D1E1AD5CB9E3967E98E901DAFCD37C44CF0BFB6C216997F5EE51DF")
|
pubX, err := hex.DecodeString("3AF1E1EFA4D1E1AD5CB9E3967E98E901DAFCD37C44CF0BFB6C216997F5EE51DF")
|
||||||
@@ -147,11 +147,11 @@ func TestSwapFactory_Claim_vec(t *testing.T) {
|
|||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|
||||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
nonce := big.NewInt(0)
|
nonce := big.NewInt(0)
|
||||||
tx, err = contract.NewSwap(auth, cmt, [32]byte{}, addr, defaultTimeoutDuration,
|
tx, err = contract.NewSwap(auth, cmt, [32]byte{}, addr, defaultTimeoutDuration,
|
||||||
@@ -168,7 +168,7 @@ func TestSwapFactory_Claim_vec(t *testing.T) {
|
|||||||
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[0])
|
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[0])
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
swap := SwapFactorySwap{
|
swap := SwapCreatorSwap{
|
||||||
Owner: addr,
|
Owner: addr,
|
||||||
Claimer: addr,
|
Claimer: addr,
|
||||||
PubKeyClaim: cmt,
|
PubKeyClaim: cmt,
|
||||||
@@ -211,19 +211,24 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
cmt := res.Secp256k1PublicKey().Keccak256()
|
cmt := res.Secp256k1PublicKey().Keccak256()
|
||||||
|
|
||||||
// deploy swap contract with claim key hash
|
// deploy swap contract with claim key hash
|
||||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
authOrig, conn, pkA := setupXMRTakerAuth(t)
|
||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|
||||||
swapFactoryAddress, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
// TODO: Rewrite this code to avoid the awkward use of txOpts. Code was using
|
||||||
|
// same TxOpts for multiple transactions and we needed a quick fix to get
|
||||||
|
// CI working.
|
||||||
|
txOpts := *authOrig
|
||||||
|
swapCreatorAddr, tx, contract, err := DeploySwapCreator(&txOpts, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
if asset != ethAssetAddress {
|
if asset != ethAssetAddress {
|
||||||
require.NotNil(t, erc20Contract)
|
require.NotNil(t, erc20Contract)
|
||||||
tx, err = erc20Contract.Approve(auth, swapFactoryAddress, value)
|
txOpts = *authOrig
|
||||||
|
tx, err = erc20Contract.Approve(&txOpts, swapCreatorAddr, value)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -231,17 +236,17 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
}
|
}
|
||||||
|
|
||||||
nonce := big.NewInt(0)
|
nonce := big.NewInt(0)
|
||||||
|
txOpts = *authOrig
|
||||||
if asset == ethAssetAddress {
|
if asset == ethAssetAddress {
|
||||||
auth.Value = value
|
txOpts.Value = value
|
||||||
}
|
}
|
||||||
|
|
||||||
tx, err = contract.NewSwap(auth, cmt, [32]byte{}, addr,
|
tx, err = contract.NewSwap(&txOpts, cmt, [32]byte{}, addr,
|
||||||
defaultTimeoutDuration, defaultTimeoutDuration, asset, value, nonce)
|
defaultTimeoutDuration, defaultTimeoutDuration, asset, value, nonce)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to call new_swap: %d", receipt.GasUsed)
|
t.Logf("gas cost to call new_swap: %d", receipt.GasUsed)
|
||||||
auth.Value = big.NewInt(0)
|
|
||||||
|
|
||||||
require.Equal(t, newLogIndex+1, len(receipt.Logs))
|
require.Equal(t, newLogIndex+1, len(receipt.Logs))
|
||||||
id, err := GetIDFromLog(receipt.Logs[newLogIndex])
|
id, err := GetIDFromLog(receipt.Logs[newLogIndex])
|
||||||
@@ -250,7 +255,7 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[newLogIndex])
|
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[newLogIndex])
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
swap := SwapFactorySwap{
|
swap := SwapCreatorSwap{
|
||||||
Owner: addr,
|
Owner: addr,
|
||||||
Claimer: addr,
|
Claimer: addr,
|
||||||
PubKeyClaim: cmt,
|
PubKeyClaim: cmt,
|
||||||
@@ -263,7 +268,8 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
}
|
}
|
||||||
|
|
||||||
// set contract to Ready
|
// set contract to Ready
|
||||||
tx, err = contract.SetReady(auth, swap)
|
txOpts = *authOrig
|
||||||
|
tx, err = contract.SetReady(&txOpts, swap)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
t.Logf("gas cost to call SetReady: %d", receipt.GasUsed)
|
t.Logf("gas cost to call SetReady: %d", receipt.GasUsed)
|
||||||
@@ -273,7 +279,8 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
var s [32]byte
|
var s [32]byte
|
||||||
secret := proof.Secret()
|
secret := proof.Secret()
|
||||||
copy(s[:], secret[:])
|
copy(s[:], secret[:])
|
||||||
tx, err = contract.Claim(auth, swap, s)
|
txOpts = *authOrig
|
||||||
|
tx, err = contract.Claim(&txOpts, swap, s)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -284,7 +291,7 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
|||||||
require.Equal(t, StageCompleted, stage)
|
require.Equal(t, StageCompleted, stage)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_Claim_random(t *testing.T) {
|
func TestSwapCreator_Claim_random(t *testing.T) {
|
||||||
testClaim(t, ethAssetAddress, 0, big.NewInt(0), nil)
|
testClaim(t, ethAssetAddress, 0, big.NewInt(0), nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,11 +311,11 @@ func testRefundBeforeT0(t *testing.T, asset ethcommon.Address, newLogIndex int)
|
|||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|
||||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
nonce := big.NewInt(0)
|
nonce := big.NewInt(0)
|
||||||
tx, err = contract.NewSwap(auth, [32]byte{}, cmt, addr, defaultTimeoutDuration, defaultTimeoutDuration,
|
tx, err = contract.NewSwap(auth, [32]byte{}, cmt, addr, defaultTimeoutDuration, defaultTimeoutDuration,
|
||||||
@@ -325,7 +332,7 @@ func testRefundBeforeT0(t *testing.T, asset ethcommon.Address, newLogIndex int)
|
|||||||
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[newLogIndex])
|
t0, t1, err := GetTimeoutsFromLog(receipt.Logs[newLogIndex])
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
swap := SwapFactorySwap{
|
swap := SwapCreatorSwap{
|
||||||
Owner: addr,
|
Owner: addr,
|
||||||
Claimer: addr,
|
Claimer: addr,
|
||||||
PubKeyClaim: [32]byte{},
|
PubKeyClaim: [32]byte{},
|
||||||
@@ -352,7 +359,7 @@ func testRefundBeforeT0(t *testing.T, asset ethcommon.Address, newLogIndex int)
|
|||||||
require.Equal(t, StageCompleted, stage)
|
require.Equal(t, StageCompleted, stage)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_Refund_beforeT0(t *testing.T) {
|
func TestSwapCreator_Refund_beforeT0(t *testing.T) {
|
||||||
testRefundBeforeT0(t, ethAssetAddress, 0)
|
testRefundBeforeT0(t, ethAssetAddress, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -372,11 +379,11 @@ func testRefundAfterT1(t *testing.T, asset ethcommon.Address, newLogIndex int) {
|
|||||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|
||||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
nonce := big.NewInt(0)
|
nonce := big.NewInt(0)
|
||||||
timeout := big.NewInt(1) // T1 expires before we get the receipt for new_swap TX
|
timeout := big.NewInt(1) // T1 expires before we get the receipt for new_swap TX
|
||||||
@@ -396,7 +403,7 @@ func testRefundAfterT1(t *testing.T, asset ethcommon.Address, newLogIndex int) {
|
|||||||
|
|
||||||
<-time.After(time.Until(time.Unix(t1.Int64()+1, 0)))
|
<-time.After(time.Until(time.Unix(t1.Int64()+1, 0)))
|
||||||
|
|
||||||
swap := SwapFactorySwap{
|
swap := SwapCreatorSwap{
|
||||||
Owner: addr,
|
Owner: addr,
|
||||||
Claimer: addr,
|
Claimer: addr,
|
||||||
PubKeyClaim: [32]byte{},
|
PubKeyClaim: [32]byte{},
|
||||||
@@ -428,11 +435,11 @@ func testRefundAfterT1(t *testing.T, asset ethcommon.Address, newLogIndex int) {
|
|||||||
require.Equal(t, StageCompleted, stage)
|
require.Equal(t, StageCompleted, stage)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_Refund_afterT1(t *testing.T) {
|
func TestSwapCreator_Refund_afterT1(t *testing.T) {
|
||||||
testRefundAfterT1(t, ethAssetAddress, 0)
|
testRefundAfterT1(t, ethAssetAddress, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
func TestSwapCreator_MultipleSwaps(t *testing.T) {
|
||||||
// test case where contract has multiple swaps happening at once
|
// test case where contract has multiple swaps happening at once
|
||||||
conn, chainID := tests.NewEthClient(t)
|
conn, chainID := tests.NewEthClient(t)
|
||||||
|
|
||||||
@@ -440,11 +447,11 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
|||||||
auth, err := bind.NewKeyedTransactorWithChainID(pkContractCreator, chainID)
|
auth, err := bind.NewKeyedTransactorWithChainID(pkContractCreator, chainID)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
const numSwaps = 16
|
const numSwaps = 16
|
||||||
type swapCase struct {
|
type swapCase struct {
|
||||||
@@ -452,7 +459,7 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
|||||||
walletKey *ecdsa.PrivateKey
|
walletKey *ecdsa.PrivateKey
|
||||||
id [32]byte
|
id [32]byte
|
||||||
secret [32]byte
|
secret [32]byte
|
||||||
swap SwapFactorySwap
|
swap SwapCreatorSwap
|
||||||
}
|
}
|
||||||
|
|
||||||
getAuth := func(sc *swapCase) *bind.TransactOpts {
|
getAuth := func(sc *swapCase) *bind.TransactOpts {
|
||||||
@@ -481,7 +488,7 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
|||||||
sc.walletKey = tests.GetTestKeyByIndex(t, i)
|
sc.walletKey = tests.GetTestKeyByIndex(t, i)
|
||||||
addrSwap := crypto.PubkeyToAddress(*sc.walletKey.Public().(*ecdsa.PublicKey))
|
addrSwap := crypto.PubkeyToAddress(*sc.walletKey.Public().(*ecdsa.PublicKey))
|
||||||
|
|
||||||
sc.swap = SwapFactorySwap{
|
sc.swap = SwapCreatorSwap{
|
||||||
Owner: addrSwap,
|
Owner: addrSwap,
|
||||||
Claimer: addrSwap,
|
Claimer: addrSwap,
|
||||||
PubKeyClaim: res.Secp256k1PublicKey().Keccak256(),
|
PubKeyClaim: res.Secp256k1PublicKey().Keccak256(),
|
||||||
@@ -21,7 +21,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Swap stage values that match the names and indexes of the Stage enum in
|
// Swap stage values that match the names and indexes of the Stage enum in
|
||||||
// the SwapFactory contract
|
// the SwapCreator contract
|
||||||
const (
|
const (
|
||||||
StageInvalid byte = iota
|
StageInvalid byte = iota
|
||||||
StagePending
|
StagePending
|
||||||
@@ -30,10 +30,10 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// SwapFactoryParsedABI is the parsed SwapFactory ABI. We can skip the error check,
|
// SwapCreatorParsedABI is the parsed SwapCreator ABI. We can skip the error check,
|
||||||
// as it can only fail if abigen generates JSON bindings that golang can't parse, in
|
// as it can only fail if abigen generates JSON bindings that golang can't parse, in
|
||||||
// which case it will be nil we'll see panics when vetting the binaries.
|
// which case it will be nil we'll see panics when vetting the binaries.
|
||||||
SwapFactoryParsedABI, _ = SwapFactoryMetaData.GetAbi()
|
SwapCreatorParsedABI, _ = SwapCreatorMetaData.GetAbi()
|
||||||
|
|
||||||
claimedTopic = common.GetTopic(common.ClaimedEventSignature)
|
claimedTopic = common.GetTopic(common.ClaimedEventSignature)
|
||||||
refundedTopic = common.GetTopic(common.RefundedEventSignature)
|
refundedTopic = common.GetTopic(common.RefundedEventSignature)
|
||||||
@@ -57,7 +57,7 @@ func StageToString(stage byte) string {
|
|||||||
|
|
||||||
// SwapID calculates and returns the same hashed swap identifier that newSwap
|
// SwapID calculates and returns the same hashed swap identifier that newSwap
|
||||||
// emits and that is used to track the on-chain stage of a swap.
|
// emits and that is used to track the on-chain stage of a swap.
|
||||||
func (sfs *SwapFactorySwap) SwapID() types.Hash {
|
func (sfs *SwapCreatorSwap) SwapID() types.Hash {
|
||||||
uint256Ty, err := abi.NewType("uint256", "", nil)
|
uint256Ty, err := abi.NewType("uint256", "", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Sprintf("failed to create uint256 type: %s", err))
|
panic(fmt.Sprintf("failed to create uint256 type: %s", err))
|
||||||
@@ -116,7 +116,7 @@ func (sfs *SwapFactorySwap) SwapID() types.Hash {
|
|||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// As long as none of the *big.Int fields are nil, this cannot fail.
|
// As long as none of the *big.Int fields are nil, this cannot fail.
|
||||||
// When receiving SwapFactorySwap objects from the database or peers in
|
// When receiving SwapCreatorSwap objects from the database or peers in
|
||||||
// JSON, all *big.Int values are pre-validated to be non-nil.
|
// JSON, all *big.Int values are pre-validated to be non-nil.
|
||||||
panic(fmt.Sprintf("failed to pack arguments: %s", err))
|
panic(fmt.Sprintf("failed to pack arguments: %s", err))
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ func GetSecretFromLog(log *ethtypes.Log, eventTopic [32]byte) (*mcrypto.PrivateS
|
|||||||
return nil, errors.New("invalid event, must be one of Claimed or Refunded")
|
return nil, errors.New("invalid event, must be one of Claimed or Refunded")
|
||||||
}
|
}
|
||||||
|
|
||||||
// abiSF, err := abi.JSON(strings.NewReader(SwapFactoryMetaData.ABI))
|
// abiSF, err := abi.JSON(strings.NewReader(SwapCreatorMetaData.ABI))
|
||||||
// if err != nil {
|
// if err != nil {
|
||||||
// return nil, err
|
// return nil, err
|
||||||
// }
|
// }
|
||||||
@@ -164,7 +164,7 @@ func CheckIfLogIDMatches(log ethtypes.Log, eventTopic, id [32]byte) (bool, error
|
|||||||
return false, errors.New("invalid event, must be one of Claimed or Refunded")
|
return false, errors.New("invalid event, must be one of Claimed or Refunded")
|
||||||
}
|
}
|
||||||
|
|
||||||
// abi, err := abi.JSON(strings.NewReader(SwapFactoryMetaData.ABI))
|
// abi, err := abi.JSON(strings.NewReader(SwapCreatorMetaData.ABI))
|
||||||
// if err != nil {
|
// if err != nil {
|
||||||
// return false, err
|
// return false, err
|
||||||
// }
|
// }
|
||||||
@@ -189,7 +189,7 @@ func CheckIfLogIDMatches(log ethtypes.Log, eventTopic, id [32]byte) (bool, error
|
|||||||
|
|
||||||
// GetIDFromLog returns the swap ID from a New log.
|
// GetIDFromLog returns the swap ID from a New log.
|
||||||
func GetIDFromLog(log *ethtypes.Log) ([32]byte, error) {
|
func GetIDFromLog(log *ethtypes.Log) ([32]byte, error) {
|
||||||
abi := SwapFactoryParsedABI
|
abi := SwapCreatorParsedABI
|
||||||
|
|
||||||
const event = "New"
|
const event = "New"
|
||||||
if log.Topics[0] != abi.Events[event].ID {
|
if log.Topics[0] != abi.Events[event].ID {
|
||||||
@@ -213,7 +213,7 @@ func GetIDFromLog(log *ethtypes.Log) ([32]byte, error) {
|
|||||||
|
|
||||||
// GetTimeoutsFromLog returns the timeouts from a New event.
|
// GetTimeoutsFromLog returns the timeouts from a New event.
|
||||||
func GetTimeoutsFromLog(log *ethtypes.Log) (*big.Int, *big.Int, error) {
|
func GetTimeoutsFromLog(log *ethtypes.Log) (*big.Int, *big.Int, error) {
|
||||||
abi := SwapFactoryParsedABI
|
abi := SwapCreatorParsedABI
|
||||||
|
|
||||||
const event = "New"
|
const event = "New"
|
||||||
if log.Topics[0] != abi.Events[event].ID {
|
if log.Topics[0] != abi.Events[event].ID {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ package watcher
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"math/big"
|
"math/big"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -13,14 +14,18 @@ import (
|
|||||||
ethcommon "github.com/ethereum/go-ethereum/common"
|
ethcommon "github.com/ethereum/go-ethereum/common"
|
||||||
ethtypes "github.com/ethereum/go-ethereum/core/types"
|
ethtypes "github.com/ethereum/go-ethereum/core/types"
|
||||||
"github.com/ethereum/go-ethereum/ethclient"
|
"github.com/ethereum/go-ethereum/ethclient"
|
||||||
|
ethrpc "github.com/ethereum/go-ethereum/rpc"
|
||||||
logging "github.com/ipfs/go-log"
|
logging "github.com/ipfs/go-log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
const (
|
||||||
log = logging.Logger("ethereum/watcher")
|
|
||||||
checkForBlocksTimeout = time.Second
|
checkForBlocksTimeout = time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
log = logging.Logger("ethereum/watcher")
|
||||||
|
)
|
||||||
|
|
||||||
// EventFilter filters the chain for specific events (logs).
|
// EventFilter filters the chain for specific events (logs).
|
||||||
// When it finds a desired log, it puts it into its outbound channel.
|
// When it finds a desired log, it puts it into its outbound channel.
|
||||||
type EventFilter struct {
|
type EventFilter struct {
|
||||||
@@ -70,6 +75,9 @@ func (f *EventFilter) Start() error {
|
|||||||
currHeader, err := f.ec.HeaderByNumber(f.ctx, nil)
|
currHeader, err := f.ec.HeaderByNumber(f.ctx, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("failed to get header in event watcher: %s", err)
|
log.Errorf("failed to get header in event watcher: %s", err)
|
||||||
|
if errors.Is(err, ethrpc.ErrClientQuit) {
|
||||||
|
return // non-recoverable error
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,7 +93,9 @@ func (f *EventFilter) Start() error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugf("filtered for logs from block %s to block %s", f.filterQuery.FromBlock, currHeader.Number)
|
// If you think we are missing log events, uncomment to debug:
|
||||||
|
// log.Debugf("filtered for logs from block %s to block %s",
|
||||||
|
// f.filterQuery.FromBlock, currHeader.Number)
|
||||||
|
|
||||||
for _, l := range logs {
|
for _, l := range logs {
|
||||||
if l.Topics[0] != f.topic {
|
if l.Topics[0] != f.topic {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
// ProtocolID is the base atomic swap network protocol ID prefix. The full ID
|
// ProtocolID is the base atomic swap network protocol ID prefix. The full ID
|
||||||
// includes the chain ID at the end.
|
// includes the chain ID at the end.
|
||||||
ProtocolID = "/atomic-swap/0.2"
|
ProtocolID = "/atomic-swap/0.3"
|
||||||
maxMessageSize = 1 << 17
|
maxMessageSize = 1 << 17
|
||||||
maxRelayMessageSize = 2048
|
maxRelayMessageSize = 2048
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -79,8 +79,14 @@ func (s *mockSwapState) Exit() error {
|
|||||||
func basicTestConfig(t *testing.T) *Config {
|
func basicTestConfig(t *testing.T) *Config {
|
||||||
// t.TempDir() is unique on every call. Don't reuse this config with multiple hosts.
|
// t.TempDir() is unique on every call. Don't reuse this config with multiple hosts.
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cancel()
|
||||||
|
})
|
||||||
|
|
||||||
return &Config{
|
return &Config{
|
||||||
Ctx: context.Background(),
|
Ctx: ctx,
|
||||||
DataDir: tmpDir,
|
DataDir: tmpDir,
|
||||||
Port: 0, // OS randomized libp2p port
|
Port: 0, // OS randomized libp2p port
|
||||||
KeyFile: path.Join(tmpDir, "node.key"),
|
KeyFile: path.Join(tmpDir, "node.key"),
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ type NotifyETHLocked struct {
|
|||||||
Address ethcommon.Address `json:"address" validate:"required"`
|
Address ethcommon.Address `json:"address" validate:"required"`
|
||||||
TxHash types.Hash `json:"txHash" validate:"required"`
|
TxHash types.Hash `json:"txHash" validate:"required"`
|
||||||
ContractSwapID types.Hash `json:"contractSwapID" validate:"required"`
|
ContractSwapID types.Hash `json:"contractSwapID" validate:"required"`
|
||||||
ContractSwap *contracts.SwapFactorySwap `json:"contractSwap" validate:"required"`
|
ContractSwap *contracts.SwapCreatorSwap `json:"contractSwap" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// String ...
|
// String ...
|
||||||
|
|||||||
@@ -18,11 +18,11 @@ type RelayClaimRequest struct {
|
|||||||
// OfferID is non-nil, if the request is from a maker to the taker of an
|
// OfferID is non-nil, if the request is from a maker to the taker of an
|
||||||
// active swap. It is nil, if the request is being sent to a relay node,
|
// active swap. It is nil, if the request is being sent to a relay node,
|
||||||
// because it advertised in the DHT.
|
// because it advertised in the DHT.
|
||||||
OfferID *types.Hash `json:"offerID"`
|
OfferID *types.Hash `json:"offerID"`
|
||||||
SwapFactoryAddress ethcommon.Address `json:"swapFactoryAddress" validate:"required"`
|
SwapCreatorAddr ethcommon.Address `json:"swapCreatorAddr" validate:"required"`
|
||||||
Swap *contracts.SwapFactorySwap `json:"swap" validate:"required"`
|
Swap *contracts.SwapCreatorSwap `json:"swap" validate:"required"`
|
||||||
Secret []byte `json:"secret" validate:"required,len=32"`
|
Secret []byte `json:"secret" validate:"required,len=32"`
|
||||||
Signature []byte `json:"signature" validate:"required,len=65"`
|
Signature []byte `json:"signature" validate:"required,len=65"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RelayClaimResponse implements common.Message for our p2p relay claim responses
|
// RelayClaimResponse implements common.Message for our p2p relay claim responses
|
||||||
|
|||||||
@@ -60,8 +60,8 @@ func createTestClaimRequest() *message.RelayClaimRequest {
|
|||||||
sig := [65]byte{0x1}
|
sig := [65]byte{0x1}
|
||||||
|
|
||||||
req := &message.RelayClaimRequest{
|
req := &message.RelayClaimRequest{
|
||||||
SwapFactoryAddress: ethcommon.Address{0x1},
|
SwapCreatorAddr: ethcommon.Address{0x1},
|
||||||
Swap: &contracts.SwapFactorySwap{
|
Swap: &contracts.SwapCreatorSwap{
|
||||||
Owner: ethcommon.Address{0x1},
|
Owner: ethcommon.Address{0x1},
|
||||||
Claimer: ethcommon.Address{0x1},
|
Claimer: ethcommon.Address{0x1},
|
||||||
PubKeyClaim: [32]byte{0x1},
|
PubKeyClaim: [32]byte{0x1},
|
||||||
|
|||||||
@@ -64,15 +64,15 @@ type Backend interface {
|
|||||||
NewTxSender(asset ethcommon.Address, erc20Contract *contracts.IERC20) (txsender.Sender, error)
|
NewTxSender(asset ethcommon.Address, erc20Contract *contracts.IERC20) (txsender.Sender, error)
|
||||||
|
|
||||||
// helpers
|
// helpers
|
||||||
NewSwapFactory(addr ethcommon.Address) (*contracts.SwapFactory, error)
|
NewSwapCreator(addr ethcommon.Address) (*contracts.SwapCreator, error)
|
||||||
HandleRelayClaimRequest(request *message.RelayClaimRequest) (*message.RelayClaimResponse, error)
|
HandleRelayClaimRequest(request *message.RelayClaimRequest) (*message.RelayClaimResponse, error)
|
||||||
|
|
||||||
// getters
|
// getters
|
||||||
Ctx() context.Context
|
Ctx() context.Context
|
||||||
Env() common.Environment
|
Env() common.Environment
|
||||||
SwapManager() swap.Manager
|
SwapManager() swap.Manager
|
||||||
Contract() *contracts.SwapFactory
|
SwapCreator() *contracts.SwapCreator
|
||||||
ContractAddr() ethcommon.Address
|
SwapCreatorAddr() ethcommon.Address
|
||||||
SwapTimeout() time.Duration
|
SwapTimeout() time.Duration
|
||||||
XMRDepositAddress(offerID *types.Hash) *mcrypto.Address
|
XMRDepositAddress(offerID *types.Hash) *mcrypto.Address
|
||||||
|
|
||||||
@@ -101,9 +101,9 @@ type backend struct {
|
|||||||
perSwapXMRDepositAddr map[types.Hash]*mcrypto.Address
|
perSwapXMRDepositAddr map[types.Hash]*mcrypto.Address
|
||||||
|
|
||||||
// swap contract
|
// swap contract
|
||||||
contract *contracts.SwapFactory
|
swapCreator *contracts.SwapCreator
|
||||||
contractAddr ethcommon.Address
|
swapCreatorAddr ethcommon.Address
|
||||||
swapTimeout time.Duration
|
swapTimeout time.Duration
|
||||||
|
|
||||||
// network interface
|
// network interface
|
||||||
NetSender
|
NetSender
|
||||||
@@ -111,23 +111,23 @@ type backend struct {
|
|||||||
|
|
||||||
// Config is the config for the Backend
|
// Config is the config for the Backend
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Ctx context.Context
|
Ctx context.Context
|
||||||
MoneroClient monero.WalletClient
|
MoneroClient monero.WalletClient
|
||||||
EthereumClient extethclient.EthClient
|
EthereumClient extethclient.EthClient
|
||||||
Environment common.Environment
|
Environment common.Environment
|
||||||
SwapFactoryAddress ethcommon.Address
|
SwapCreatorAddr ethcommon.Address
|
||||||
SwapManager swap.Manager
|
SwapManager swap.Manager
|
||||||
RecoveryDB RecoveryDB
|
RecoveryDB RecoveryDB
|
||||||
Net NetSender
|
Net NetSender
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewBackend returns a new Backend
|
// NewBackend returns a new Backend
|
||||||
func NewBackend(cfg *Config) (Backend, error) {
|
func NewBackend(cfg *Config) (Backend, error) {
|
||||||
if (cfg.SwapFactoryAddress == ethcommon.Address{}) {
|
if (cfg.SwapCreatorAddr == ethcommon.Address{}) {
|
||||||
return nil, errNilSwapContractOrAddress
|
return nil, errNilSwapContractOrAddress
|
||||||
}
|
}
|
||||||
|
|
||||||
swapFactory, err := contracts.NewSwapFactory(cfg.SwapFactoryAddress, cfg.EthereumClient.Raw())
|
swapCreator, err := contracts.NewSwapCreator(cfg.SwapCreatorAddr, cfg.EthereumClient.Raw())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -137,8 +137,8 @@ func NewBackend(cfg *Config) (Backend, error) {
|
|||||||
env: cfg.Environment,
|
env: cfg.Environment,
|
||||||
moneroWallet: cfg.MoneroClient,
|
moneroWallet: cfg.MoneroClient,
|
||||||
ethClient: cfg.EthereumClient,
|
ethClient: cfg.EthereumClient,
|
||||||
contract: swapFactory,
|
swapCreator: swapCreator,
|
||||||
contractAddr: cfg.SwapFactoryAddress,
|
swapCreatorAddr: cfg.SwapCreatorAddr,
|
||||||
swapManager: cfg.SwapManager,
|
swapManager: cfg.SwapManager,
|
||||||
swapTimeout: common.SwapTimeoutFromEnv(cfg.Environment),
|
swapTimeout: common.SwapTimeoutFromEnv(cfg.Environment),
|
||||||
NetSender: cfg.Net,
|
NetSender: cfg.Net,
|
||||||
@@ -157,22 +157,22 @@ func (b *backend) ETHClient() extethclient.EthClient {
|
|||||||
|
|
||||||
func (b *backend) NewTxSender(asset ethcommon.Address, erc20Contract *contracts.IERC20) (txsender.Sender, error) {
|
func (b *backend) NewTxSender(asset ethcommon.Address, erc20Contract *contracts.IERC20) (txsender.Sender, error) {
|
||||||
if !b.ethClient.HasPrivateKey() {
|
if !b.ethClient.HasPrivateKey() {
|
||||||
return txsender.NewExternalSender(b.ctx, b.env, b.ethClient.Raw(), b.contractAddr, asset)
|
return txsender.NewExternalSender(b.ctx, b.env, b.ethClient.Raw(), b.swapCreatorAddr, asset)
|
||||||
}
|
}
|
||||||
|
|
||||||
return txsender.NewSenderWithPrivateKey(b.ctx, b.ETHClient(), b.contract, erc20Contract), nil
|
return txsender.NewSenderWithPrivateKey(b.ctx, b.ETHClient(), b.swapCreator, erc20Contract), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *backend) RecoveryDB() RecoveryDB {
|
func (b *backend) RecoveryDB() RecoveryDB {
|
||||||
return b.recoveryDB
|
return b.recoveryDB
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *backend) Contract() *contracts.SwapFactory {
|
func (b *backend) SwapCreator() *contracts.SwapCreator {
|
||||||
return b.contract
|
return b.swapCreator
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *backend) ContractAddr() ethcommon.Address {
|
func (b *backend) SwapCreatorAddr() ethcommon.Address {
|
||||||
return b.contractAddr
|
return b.swapCreatorAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *backend) Ctx() context.Context {
|
func (b *backend) Ctx() context.Context {
|
||||||
@@ -197,8 +197,8 @@ func (b *backend) SetSwapTimeout(timeout time.Duration) {
|
|||||||
b.swapTimeout = timeout
|
b.swapTimeout = timeout
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *backend) NewSwapFactory(addr ethcommon.Address) (*contracts.SwapFactory, error) {
|
func (b *backend) NewSwapCreator(addr ethcommon.Address) (*contracts.SwapCreator, error) {
|
||||||
return contracts.NewSwapFactory(addr, b.ethClient.Raw())
|
return contracts.NewSwapCreator(addr, b.ethClient.Raw())
|
||||||
}
|
}
|
||||||
|
|
||||||
// XMRDepositAddress returns the per-swap override deposit address, if a
|
// XMRDepositAddress returns the per-swap override deposit address, if a
|
||||||
@@ -258,6 +258,6 @@ func (b *backend) HandleRelayClaimRequest(request *message.RelayClaimRequest) (*
|
|||||||
b.Ctx(),
|
b.Ctx(),
|
||||||
request,
|
request,
|
||||||
b.ETHClient(),
|
b.ETHClient(),
|
||||||
b.ContractAddr(),
|
b.SwapCreatorAddr(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
// CurInfoVersion is the latest supported version of a serialised Info struct
|
// CurInfoVersion is the latest supported version of a serialised Info struct
|
||||||
CurInfoVersion, _ = semver.NewVersion("0.2.0")
|
CurInfoVersion, _ = semver.NewVersion("0.3.0")
|
||||||
|
|
||||||
errInfoVersionMissing = errors.New("required 'version' field missing in swap Info")
|
errInfoVersionMissing = errors.New("required 'version' field missing in swap Info")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ func Test_InfoMarshal(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
expectedJSON := `{
|
expectedJSON := `{
|
||||||
"version": "0.2.0",
|
"version": "0.3.0",
|
||||||
"peerID": "12D3KooWQQRJuKTZ35eiHGNPGDpQqjpJSdaxEMJRxi6NWFrrvQVi",
|
"peerID": "12D3KooWQQRJuKTZ35eiHGNPGDpQqjpJSdaxEMJRxi6NWFrrvQVi",
|
||||||
"offerID": "0x0102030405060708091011121314151617181920212223242526272829303132",
|
"offerID": "0x0102030405060708091011121314151617181920212223242526272829303132",
|
||||||
"provides": "XMR",
|
"provides": "XMR",
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ func NewExternalSender(
|
|||||||
return &ExternalSender{
|
return &ExternalSender{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
ec: ec,
|
ec: ec,
|
||||||
abi: contracts.SwapFactoryParsedABI,
|
abi: contracts.SwapCreatorParsedABI,
|
||||||
contractAddr: contractAddr,
|
contractAddr: contractAddr,
|
||||||
erc20Addr: erc20Addr,
|
erc20Addr: erc20Addr,
|
||||||
out: make(chan *Transaction),
|
out: make(chan *Transaction),
|
||||||
@@ -77,7 +77,7 @@ func NewExternalSender(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetContract ...
|
// SetContract ...
|
||||||
func (s *ExternalSender) SetContract(_ *contracts.SwapFactory) {}
|
func (s *ExternalSender) SetContract(_ *contracts.SwapCreator) {}
|
||||||
|
|
||||||
// SetContractAddress ...
|
// SetContractAddress ...
|
||||||
func (s *ExternalSender) SetContractAddress(addr ethcommon.Address) {
|
func (s *ExternalSender) SetContractAddress(addr ethcommon.Address) {
|
||||||
@@ -150,7 +150,7 @@ func (s *ExternalSender) NewSwap(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetReady prompts the external sender to sign a set_ready transaction
|
// SetReady prompts the external sender to sign a set_ready transaction
|
||||||
func (s *ExternalSender) SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.Receipt, error) {
|
func (s *ExternalSender) SetReady(swap *contracts.SwapCreatorSwap) (*ethtypes.Receipt, error) {
|
||||||
input, err := s.abi.Pack("set_ready", swap)
|
input, err := s.abi.Pack("set_ready", swap)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -161,7 +161,7 @@ func (s *ExternalSender) SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.Re
|
|||||||
|
|
||||||
// Claim prompts the external sender to sign a claim transaction
|
// Claim prompts the external sender to sign a claim transaction
|
||||||
func (s *ExternalSender) Claim(
|
func (s *ExternalSender) Claim(
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret [32]byte,
|
secret [32]byte,
|
||||||
) (*ethtypes.Receipt, error) {
|
) (*ethtypes.Receipt, error) {
|
||||||
input, err := s.abi.Pack("claim", swap, secret)
|
input, err := s.abi.Pack("claim", swap, secret)
|
||||||
@@ -174,7 +174,7 @@ func (s *ExternalSender) Claim(
|
|||||||
|
|
||||||
// Refund prompts the external sender to sign a refund transaction
|
// Refund prompts the external sender to sign a refund transaction
|
||||||
func (s *ExternalSender) Refund(
|
func (s *ExternalSender) Refund(
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret [32]byte,
|
secret [32]byte,
|
||||||
) (*ethtypes.Receipt, error) {
|
) (*ethtypes.Receipt, error) {
|
||||||
input, err := s.abi.Pack("refund", swap, secret)
|
input, err := s.abi.Pack("refund", swap, secret)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import (
|
|||||||
|
|
||||||
// Sender signs and submits transactions to the chain
|
// Sender signs and submits transactions to the chain
|
||||||
type Sender interface {
|
type Sender interface {
|
||||||
SetContract(*contracts.SwapFactory)
|
SetContract(*contracts.SwapCreator)
|
||||||
SetContractAddress(ethcommon.Address)
|
SetContractAddress(ethcommon.Address)
|
||||||
Approve(spender ethcommon.Address, amount *big.Int) (*ethtypes.Receipt, error) // for ERC20 swaps
|
Approve(spender ethcommon.Address, amount *big.Int) (*ethtypes.Receipt, error) // for ERC20 swaps
|
||||||
NewSwap(
|
NewSwap(
|
||||||
@@ -36,15 +36,15 @@ type Sender interface {
|
|||||||
ethAsset types.EthAsset,
|
ethAsset types.EthAsset,
|
||||||
amount *big.Int,
|
amount *big.Int,
|
||||||
) (*ethtypes.Receipt, error)
|
) (*ethtypes.Receipt, error)
|
||||||
SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.Receipt, error)
|
SetReady(swap *contracts.SwapCreatorSwap) (*ethtypes.Receipt, error)
|
||||||
Claim(swap *contracts.SwapFactorySwap, secret [32]byte) (*ethtypes.Receipt, error)
|
Claim(swap *contracts.SwapCreatorSwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||||
Refund(swap *contracts.SwapFactorySwap, secret [32]byte) (*ethtypes.Receipt, error)
|
Refund(swap *contracts.SwapCreatorSwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type privateKeySender struct {
|
type privateKeySender struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
ethClient extethclient.EthClient
|
ethClient extethclient.EthClient
|
||||||
swapContract *contracts.SwapFactory
|
swapContract *contracts.SwapCreator
|
||||||
erc20Contract *contracts.IERC20
|
erc20Contract *contracts.IERC20
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ type privateKeySender struct {
|
|||||||
func NewSenderWithPrivateKey(
|
func NewSenderWithPrivateKey(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
ethClient extethclient.EthClient,
|
ethClient extethclient.EthClient,
|
||||||
swapContract *contracts.SwapFactory,
|
swapContract *contracts.SwapCreator,
|
||||||
erc20Contract *contracts.IERC20,
|
erc20Contract *contracts.IERC20,
|
||||||
) Sender {
|
) Sender {
|
||||||
return &privateKeySender{
|
return &privateKeySender{
|
||||||
@@ -63,7 +63,7 @@ func NewSenderWithPrivateKey(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *privateKeySender) SetContract(contract *contracts.SwapFactory) {
|
func (s *privateKeySender) SetContract(contract *contracts.SwapCreator) {
|
||||||
s.swapContract = contract
|
s.swapContract = contract
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,7 +132,7 @@ func (s *privateKeySender) NewSwap(
|
|||||||
return receipt, nil
|
return receipt, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *privateKeySender) SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.Receipt, error) {
|
func (s *privateKeySender) SetReady(swap *contracts.SwapCreatorSwap) (*ethtypes.Receipt, error) {
|
||||||
s.ethClient.Lock()
|
s.ethClient.Lock()
|
||||||
defer s.ethClient.Unlock()
|
defer s.ethClient.Unlock()
|
||||||
txOpts, err := s.ethClient.TxOpts(s.ctx)
|
txOpts, err := s.ethClient.TxOpts(s.ctx)
|
||||||
@@ -156,7 +156,7 @@ func (s *privateKeySender) SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *privateKeySender) Claim(
|
func (s *privateKeySender) Claim(
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret [32]byte,
|
secret [32]byte,
|
||||||
) (*ethtypes.Receipt, error) {
|
) (*ethtypes.Receipt, error) {
|
||||||
s.ethClient.Lock()
|
s.ethClient.Lock()
|
||||||
@@ -182,7 +182,7 @@ func (s *privateKeySender) Claim(
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *privateKeySender) Refund(
|
func (s *privateKeySender) Refund(
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret [32]byte,
|
secret [32]byte,
|
||||||
) (*ethtypes.Receipt, error) {
|
) (*ethtypes.Receipt, error) {
|
||||||
s.ethClient.Lock()
|
s.ethClient.Lock()
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ func (s *swapState) checkContract(txHash ethcommon.Hash) error {
|
|||||||
return fmt.Errorf("failed to get newSwap transaction %s by hash: %w", txHash, err)
|
return fmt.Errorf("failed to get newSwap transaction %s by hash: %w", txHash, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if tx.To() == nil || *(tx.To()) != s.contractAddr {
|
if tx.To() == nil || *(tx.To()) != s.swapCreatorAddr {
|
||||||
return errInvalidETHLockedTransaction
|
return errInvalidETHLockedTransaction
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,9 +45,9 @@ func (s *swapState) checkContract(txHash ethcommon.Hash) error {
|
|||||||
return errCannotFindNewLog
|
return errCannotFindNewLog
|
||||||
}
|
}
|
||||||
|
|
||||||
var event *contracts.SwapFactoryNew
|
var event *contracts.SwapCreatorNew
|
||||||
for _, log := range receipt.Logs {
|
for _, log := range receipt.Logs {
|
||||||
event, err = s.Contract().ParseNew(*log)
|
event, err = s.SwapCreator().ParseNew(*log)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ func (s *swapState) relayClaimWithXMRTaker(request *message.RelayClaimRequest) (
|
|||||||
s.ctx,
|
s.ctx,
|
||||||
s.ETHClient().Raw(),
|
s.ETHClient().Raw(),
|
||||||
response.TxHash,
|
response.TxHash,
|
||||||
s.contractAddr,
|
s.swapCreatorAddr,
|
||||||
s.contractSwapID,
|
s.contractSwapID,
|
||||||
s.getSecret(),
|
s.getSecret(),
|
||||||
)
|
)
|
||||||
@@ -159,7 +159,7 @@ func (s *swapState) claimWithAdvertisedRelayers(request *message.RelayClaimReque
|
|||||||
s.ctx,
|
s.ctx,
|
||||||
s.ETHClient().Raw(),
|
s.ETHClient().Raw(),
|
||||||
resp.TxHash,
|
resp.TxHash,
|
||||||
s.contractAddr,
|
s.swapCreatorAddr,
|
||||||
s.contractSwapID,
|
s.contractSwapID,
|
||||||
s.getSecret(),
|
s.getSecret(),
|
||||||
)
|
)
|
||||||
@@ -183,7 +183,7 @@ func (s *swapState) claimWithAdvertisedRelayers(request *message.RelayClaimReque
|
|||||||
// operations more generally. Note that the receipt returned is for a
|
// operations more generally. Note that the receipt returned is for a
|
||||||
// transaction created by the remote relayer, not by us.
|
// transaction created by the remote relayer, not by us.
|
||||||
func (s *swapState) claimWithRelay() (*ethtypes.Receipt, error) {
|
func (s *swapState) claimWithRelay() (*ethtypes.Receipt, error) {
|
||||||
forwarderAddress, err := s.Contract().TrustedForwarder(&bind.CallOpts{Context: s.ctx})
|
forwarderAddr, err := s.SwapCreator().TrustedForwarder(&bind.CallOpts{Context: s.ctx})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -194,8 +194,8 @@ func (s *swapState) claimWithRelay() (*ethtypes.Receipt, error) {
|
|||||||
s.ctx,
|
s.ctx,
|
||||||
s.ETHClient().PrivateKey(),
|
s.ETHClient().PrivateKey(),
|
||||||
s.ETHClient().Raw(),
|
s.ETHClient().Raw(),
|
||||||
s.contractAddr,
|
s.swapCreatorAddr,
|
||||||
forwarderAddress,
|
forwarderAddr,
|
||||||
s.contractSwap,
|
s.contractSwap,
|
||||||
&secret,
|
&secret,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
|||||||
addr := crypto.PubkeyToAddress(*pub)
|
addr := crypto.PubkeyToAddress(*pub)
|
||||||
|
|
||||||
// deploy forwarder
|
// deploy forwarder
|
||||||
forwarderAddress, tx, forwarderContract, err := gsnforwarder.DeployForwarder(txOpts, ec.Raw())
|
forwarderAddr, tx, forwarderContract, err := gsnforwarder.DeployForwarder(txOpts, ec.Raw())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
receipt, err := block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -97,11 +97,11 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
|||||||
t.Logf("gas cost to call RegisterDomainSeparator: %d", receipt.GasUsed)
|
t.Logf("gas cost to call RegisterDomainSeparator: %d", receipt.GasUsed)
|
||||||
|
|
||||||
// deploy swap contract with claim key hash
|
// deploy swap contract with claim key hash
|
||||||
contractAddr, tx, contract, err := contracts.DeploySwapFactory(txOpts, ec.Raw(), forwarderAddress)
|
contractAddr, tx, contract, err := contracts.DeploySwapCreator(txOpts, ec.Raw(), forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err = block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
receipt, err = block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
t.Logf("gas cost to deploy SwapFactory.sol: %d", receipt.GasUsed)
|
t.Logf("gas cost to deploy SwapCreator.sol: %d", receipt.GasUsed)
|
||||||
|
|
||||||
if asset != types.EthAssetETH {
|
if asset != types.EthAssetETH {
|
||||||
token, err := contracts.NewIERC20(asset.Address(), ec.Raw()) //nolint:govet
|
token, err := contracts.NewIERC20(asset.Address(), ec.Raw()) //nolint:govet
|
||||||
@@ -141,7 +141,7 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
|||||||
t0, t1, err := contracts.GetTimeoutsFromLog(receipt.Logs[logIndex])
|
t0, t1, err := contracts.GetTimeoutsFromLog(receipt.Logs[logIndex])
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
swap := &contracts.SwapFactorySwap{
|
swap := &contracts.SwapCreatorSwap{
|
||||||
Owner: addr,
|
Owner: addr,
|
||||||
Claimer: addr,
|
Claimer: addr,
|
||||||
PubKeyClaim: cmt,
|
PubKeyClaim: cmt,
|
||||||
@@ -168,7 +168,7 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
|||||||
sk,
|
sk,
|
||||||
ec.Raw(),
|
ec.Raw(),
|
||||||
contractAddr,
|
contractAddr,
|
||||||
forwarderAddress,
|
forwarderAddr,
|
||||||
swap,
|
swap,
|
||||||
&secret,
|
&secret,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ func TestSwapState_handleEvent_EventContractReady(t *testing.T) {
|
|||||||
|
|
||||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := s.Contract().SetReady(txOpts, *s.contractSwap)
|
tx, err := s.SwapCreator().SetReady(txOpts, *s.contractSwap)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tests.MineTransaction(t, s.ETHClient().Raw(), tx)
|
tests.MineTransaction(t, s.ETHClient().Raw(), tx)
|
||||||
|
|
||||||
|
|||||||
@@ -88,8 +88,8 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
|||||||
txOpts, err := bind.NewKeyedTransactorWithChainID(pk, chainID)
|
txOpts, err := bind.NewKeyedTransactorWithChainID(pk, chainID)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
var forwarderAddress ethcommon.Address
|
var forwarderAddr ethcommon.Address
|
||||||
_, tx, _, err := contracts.DeploySwapFactory(txOpts, ec, forwarderAddress)
|
_, tx, _, err := contracts.DeploySwapCreator(txOpts, ec, forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
@@ -115,14 +115,14 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
|||||||
|
|
||||||
net := new(mockNet)
|
net := new(mockNet)
|
||||||
bcfg := &backend.Config{
|
bcfg := &backend.Config{
|
||||||
Ctx: ctx,
|
Ctx: ctx,
|
||||||
MoneroClient: monero.CreateWalletClient(t),
|
MoneroClient: monero.CreateWalletClient(t),
|
||||||
EthereumClient: extendedEC,
|
EthereumClient: extendedEC,
|
||||||
Environment: common.Development,
|
Environment: common.Development,
|
||||||
SwapFactoryAddress: addr,
|
SwapCreatorAddr: addr,
|
||||||
SwapManager: newSwapManager(t),
|
SwapManager: newSwapManager(t),
|
||||||
Net: net,
|
Net: net,
|
||||||
RecoveryDB: rdb,
|
RecoveryDB: rdb,
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := backend.NewBackend(bcfg)
|
b, err := backend.NewBackend(bcfg)
|
||||||
@@ -168,7 +168,7 @@ func TestInstance_createOngoingSwap(t *testing.T) {
|
|||||||
rdb := inst.backend.RecoveryDB().(*backend.MockRecoveryDB)
|
rdb := inst.backend.RecoveryDB().(*backend.MockRecoveryDB)
|
||||||
|
|
||||||
ec := inst.backend.ETHClient()
|
ec := inst.backend.ETHClient()
|
||||||
contract := inst.backend.Contract()
|
contract := inst.backend.SwapCreator()
|
||||||
contractSwap, contractSwapID, _ := newTestSwap(
|
contractSwap, contractSwapID, _ := newTestSwap(
|
||||||
t, ec, contract, [32]byte{}, [32]byte{}, big.NewInt(100), time.Minute*10,
|
t, ec, contract, [32]byte{}, [32]byte{}, big.NewInt(100), time.Minute*10,
|
||||||
)
|
)
|
||||||
@@ -204,9 +204,9 @@ func TestInstance_createOngoingSwap(t *testing.T) {
|
|||||||
rdb.EXPECT().GetCounterpartySwapPrivateKey(s.OfferID).Return(nil, errors.New("some error"))
|
rdb.EXPECT().GetCounterpartySwapPrivateKey(s.OfferID).Return(nil, errors.New("some error"))
|
||||||
rdb.EXPECT().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
rdb.EXPECT().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
||||||
StartNumber: big.NewInt(1),
|
StartNumber: big.NewInt(1),
|
||||||
ContractAddress: inst.backend.ContractAddr(),
|
SwapCreatorAddr: inst.backend.SwapCreatorAddr(),
|
||||||
SwapID: contractSwapID,
|
SwapID: contractSwapID,
|
||||||
Swap: &contracts.SwapFactorySwap{
|
Swap: &contracts.SwapCreatorSwap{
|
||||||
Timeout0: big.NewInt(1),
|
Timeout0: big.NewInt(1),
|
||||||
Timeout1: big.NewInt(2),
|
Timeout1: big.NewInt(2),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ func (s *swapState) handleNotifyETHLocked(msg *message.NotifyETHLocked) error {
|
|||||||
// note: this function verifies the forwarder code as well, even if we aren't using a relayer,
|
// note: this function verifies the forwarder code as well, even if we aren't using a relayer,
|
||||||
// in which case it's not relevant to us and we don't need to verify it.
|
// in which case it's not relevant to us and we don't need to verify it.
|
||||||
// doesn't hurt though I suppose.
|
// doesn't hurt though I suppose.
|
||||||
_, err = contracts.CheckSwapFactoryContractCode(s.ctx, s.Backend.ETHClient().Raw(), contractAddr)
|
_, err = contracts.CheckSwapCreatorContractCode(s.ctx, s.Backend.ETHClient().Raw(), contractAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ func (s *swapState) handleNotifyETHLocked(msg *message.NotifyETHLocked) error {
|
|||||||
StartNumber: receipt.BlockNumber,
|
StartNumber: receipt.BlockNumber,
|
||||||
SwapID: s.contractSwapID,
|
SwapID: s.contractSwapID,
|
||||||
Swap: s.contractSwap,
|
Swap: s.contractSwap,
|
||||||
ContractAddress: contractAddr,
|
SwapCreatorAddr: contractAddr,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = s.Backend.RecoveryDB().PutContractSwapInfo(s.OfferID(), ethInfo); err != nil {
|
if err = s.Backend.RecoveryDB().PutContractSwapInfo(s.OfferID(), ethInfo); err != nil {
|
||||||
|
|||||||
@@ -63,11 +63,11 @@ type swapState struct {
|
|||||||
pubkeys *mcrypto.PublicKeyPair
|
pubkeys *mcrypto.PublicKeyPair
|
||||||
|
|
||||||
// swap contract and timeouts in it
|
// swap contract and timeouts in it
|
||||||
contract *contracts.SwapFactory
|
contract *contracts.SwapCreator
|
||||||
contractAddr ethcommon.Address
|
swapCreatorAddr ethcommon.Address
|
||||||
contractSwapID [32]byte
|
contractSwapID [32]byte
|
||||||
contractSwap *contracts.SwapFactorySwap
|
contractSwap *contracts.SwapCreatorSwap
|
||||||
t0, t1 time.Time
|
t0, t1 time.Time
|
||||||
|
|
||||||
// XMRTaker's keys for this session
|
// XMRTaker's keys for this session
|
||||||
xmrtakerPublicSpendKey *mcrypto.PublicKey
|
xmrtakerPublicSpendKey *mcrypto.PublicKey
|
||||||
@@ -182,7 +182,7 @@ func checkIfAlreadyClaimed(
|
|||||||
) (bool, error) {
|
) (bool, error) {
|
||||||
// check if swap actually completed and we didn't realize for some reason
|
// check if swap actually completed and we didn't realize for some reason
|
||||||
// this could happen if we restart from an ongoing swap
|
// this could happen if we restart from an ongoing swap
|
||||||
contract, err := contracts.NewSwapFactory(ethSwapInfo.ContractAddress, b.ETHClient().Raw())
|
contract, err := contracts.NewSwapCreator(ethSwapInfo.SwapCreatorAddr, b.ETHClient().Raw())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
@@ -206,7 +206,7 @@ func checkIfAlreadyClaimed(
|
|||||||
|
|
||||||
filterQuery := ethereum.FilterQuery{
|
filterQuery := ethereum.FilterQuery{
|
||||||
FromBlock: ethSwapInfo.StartNumber,
|
FromBlock: ethSwapInfo.StartNumber,
|
||||||
Addresses: []ethcommon.Address{ethSwapInfo.ContractAddress},
|
Addresses: []ethcommon.Address{ethSwapInfo.SwapCreatorAddr},
|
||||||
}
|
}
|
||||||
|
|
||||||
claimedTopic := common.GetTopic(common.ClaimedEventSignature)
|
claimedTopic := common.GetTopic(common.ClaimedEventSignature)
|
||||||
@@ -309,7 +309,7 @@ func newSwapStateFromOngoing(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = s.setContract(ethSwapInfo.ContractAddress)
|
err = s.setContract(ethSwapInfo.SwapCreatorAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -361,7 +361,7 @@ func newSwapState(
|
|||||||
readyWatcher := watcher.NewEventFilter(
|
readyWatcher := watcher.NewEventFilter(
|
||||||
ctx,
|
ctx,
|
||||||
b.ETHClient().Raw(),
|
b.ETHClient().Raw(),
|
||||||
b.ContractAddr(),
|
b.SwapCreatorAddr(),
|
||||||
ethStartNumber,
|
ethStartNumber,
|
||||||
readyTopic,
|
readyTopic,
|
||||||
logReadyCh,
|
logReadyCh,
|
||||||
@@ -370,7 +370,7 @@ func newSwapState(
|
|||||||
refundedWatcher := watcher.NewEventFilter(
|
refundedWatcher := watcher.NewEventFilter(
|
||||||
ctx,
|
ctx,
|
||||||
b.ETHClient().Raw(),
|
b.ETHClient().Raw(),
|
||||||
b.ContractAddr(),
|
b.SwapCreatorAddr(),
|
||||||
ethStartNumber,
|
ethStartNumber,
|
||||||
refundedTopic,
|
refundedTopic,
|
||||||
logRefundedCh,
|
logRefundedCh,
|
||||||
@@ -624,10 +624,10 @@ func (s *swapState) setXMRTakerKeys(
|
|||||||
|
|
||||||
// setContract sets the contract in which XMRTaker has locked her ETH.
|
// setContract sets the contract in which XMRTaker has locked her ETH.
|
||||||
func (s *swapState) setContract(address ethcommon.Address) error {
|
func (s *swapState) setContract(address ethcommon.Address) error {
|
||||||
s.contractAddr = address
|
s.swapCreatorAddr = address
|
||||||
|
|
||||||
var err error
|
var err error
|
||||||
s.contract, err = s.NewSwapFactory(address)
|
s.contract, err = s.NewSwapCreator(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func TestSwapStateOngoing_ClaimFunds(t *testing.T) {
|
|||||||
|
|
||||||
txOpts, err := swapState.ETHClient().TxOpts(swapState.Backend.Ctx())
|
txOpts, err := swapState.ETHClient().TxOpts(swapState.Backend.Ctx())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := swapState.Contract().SetReady(txOpts, *swapState.contractSwap)
|
tx, err := swapState.SwapCreator().SetReady(txOpts, *swapState.contractSwap)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ func TestSwapStateOngoing_ClaimFunds(t *testing.T) {
|
|||||||
StartNumber: big.NewInt(int64(startNum)),
|
StartNumber: big.NewInt(int64(startNum)),
|
||||||
SwapID: swapState.contractSwapID,
|
SwapID: swapState.contractSwapID,
|
||||||
Swap: swapState.contractSwap,
|
Swap: swapState.contractSwap,
|
||||||
ContractAddress: swapState.Backend.ContractAddr(),
|
SwapCreatorAddr: swapState.Backend.SwapCreatorAddr(),
|
||||||
}
|
}
|
||||||
|
|
||||||
swapState.info.Status = types.XMRLocked
|
swapState.info.Status = types.XMRLocked
|
||||||
@@ -101,7 +101,7 @@ func TestSwapStateOngoing_Refund(t *testing.T) {
|
|||||||
ctx := s.Backend.Ctx()
|
ctx := s.Backend.Ctx()
|
||||||
txOpts, err := s.ETHClient().TxOpts(ctx)
|
txOpts, err := s.ETHClient().TxOpts(ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := s.Contract().Refund(txOpts, *s.contractSwap, sc)
|
tx, err := s.SwapCreator().Refund(txOpts, *s.contractSwap, sc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(ctx, s.ETHClient().Raw(), tx.Hash())
|
receipt, err := block.WaitForReceipt(ctx, s.ETHClient().Raw(), tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -111,7 +111,7 @@ func TestSwapStateOngoing_Refund(t *testing.T) {
|
|||||||
StartNumber: big.NewInt(int64(startNum)),
|
StartNumber: big.NewInt(int64(startNum)),
|
||||||
SwapID: s.contractSwapID,
|
SwapID: s.contractSwapID,
|
||||||
Swap: s.contractSwap,
|
Swap: s.contractSwap,
|
||||||
ContractAddress: s.Backend.ContractAddr(),
|
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||||
}
|
}
|
||||||
|
|
||||||
s.info.Status = types.XMRLocked
|
s.info.Status = types.XMRLocked
|
||||||
|
|||||||
@@ -75,11 +75,11 @@ func newTestXMRTakerSendKeysMessage(t *testing.T) (*message.SendKeysMessage, *pc
|
|||||||
func newTestSwap(
|
func newTestSwap(
|
||||||
t *testing.T,
|
t *testing.T,
|
||||||
ec extethclient.EthClient,
|
ec extethclient.EthClient,
|
||||||
contract *contracts.SwapFactory,
|
contract *contracts.SwapCreator,
|
||||||
claimKey, refundKey types.Hash,
|
claimKey, refundKey types.Hash,
|
||||||
amount *big.Int,
|
amount *big.Int,
|
||||||
timeout time.Duration,
|
timeout time.Duration,
|
||||||
) (*contracts.SwapFactorySwap, [32]byte, ethcommon.Hash) {
|
) (*contracts.SwapCreatorSwap, [32]byte, ethcommon.Hash) {
|
||||||
tm := big.NewInt(int64(timeout.Seconds()))
|
tm := big.NewInt(int64(timeout.Seconds()))
|
||||||
txOpts, err := ec.TxOpts(context.Background())
|
txOpts, err := ec.TxOpts(context.Background())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -100,7 +100,7 @@ func newTestSwap(
|
|||||||
t0, t1, err := contracts.GetTimeoutsFromLog(receipt.Logs[0])
|
t0, t1, err := contracts.GetTimeoutsFromLog(receipt.Logs[0])
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
contractSwap := &contracts.SwapFactorySwap{
|
contractSwap := &contracts.SwapCreatorSwap{
|
||||||
Owner: ethAddr,
|
Owner: ethAddr,
|
||||||
Claimer: ethAddr,
|
Claimer: ethAddr,
|
||||||
PubKeyClaim: claimKey,
|
PubKeyClaim: claimKey,
|
||||||
@@ -128,7 +128,7 @@ func newSwap(
|
|||||||
}
|
}
|
||||||
|
|
||||||
contractSwap, contractSwapID, txHash := newTestSwap(
|
contractSwap, contractSwapID, txHash := newTestSwap(
|
||||||
t, ss.ETHClient(), ss.Contract(), claimKey, refundKey, amount, timeout,
|
t, ss.ETHClient(), ss.SwapCreator(), claimKey, refundKey, amount, timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
ss.contractSwapID = contractSwapID
|
ss.contractSwapID = contractSwapID
|
||||||
@@ -153,7 +153,7 @@ func TestSwapState_ClaimFunds(t *testing.T) {
|
|||||||
|
|
||||||
txOpts, err := swapState.ETHClient().TxOpts(swapState.ctx)
|
txOpts, err := swapState.ETHClient().TxOpts(swapState.ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := swapState.Contract().SetReady(txOpts, *swapState.contractSwap)
|
tx, err := swapState.SwapCreator().SetReady(txOpts, *swapState.contractSwap)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
||||||
|
|
||||||
@@ -201,7 +201,7 @@ func TestSwapState_HandleProtocolMessage_NotifyETHLocked_ok(t *testing.T) {
|
|||||||
duration := common.SwapTimeoutFromEnv(common.Development)
|
duration := common.SwapTimeoutFromEnv(common.Development)
|
||||||
hash := newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
hash := newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
||||||
desiredAmount.BigInt(), duration)
|
desiredAmount.BigInt(), duration)
|
||||||
addr := s.ContractAddr()
|
addr := s.SwapCreatorAddr()
|
||||||
|
|
||||||
msg = &message.NotifyETHLocked{
|
msg = &message.NotifyETHLocked{
|
||||||
Address: addr,
|
Address: addr,
|
||||||
@@ -235,7 +235,7 @@ func TestSwapState_HandleProtocolMessage_NotifyETHLocked_timeout(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_ = newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
_ = newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
||||||
desiredAmount.BigInt(), duration)
|
desiredAmount.BigInt(), duration)
|
||||||
addr := s.ContractAddr()
|
addr := s.SwapCreatorAddr()
|
||||||
|
|
||||||
err = s.setContract(addr)
|
err = s.setContract(addr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -287,7 +287,7 @@ func TestSwapState_handleRefund(t *testing.T) {
|
|||||||
|
|
||||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := s.Contract().Refund(txOpts, *s.contractSwap, sc)
|
tx, err := s.SwapCreator().Refund(txOpts, *s.contractSwap, sc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt, err := block.WaitForReceipt(s.Backend.Ctx(), s.ETHClient().Raw(), tx.Hash())
|
receipt, err := block.WaitForReceipt(s.Backend.Ctx(), s.ETHClient().Raw(), tx.Hash())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -342,7 +342,7 @@ func TestSwapState_Exit_Reclaim(t *testing.T) {
|
|||||||
|
|
||||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tx, err := s.Contract().Refund(txOpts, *s.contractSwap, sc)
|
tx, err := s.SwapCreator().Refund(txOpts, *s.contractSwap, sc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
receipt := tests.MineTransaction(t, s.ETHClient().Raw(), tx)
|
receipt := tests.MineTransaction(t, s.ETHClient().Raw(), tx)
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func (s *swapState) tryClaim() error {
|
|||||||
|
|
||||||
func (s *swapState) filterForClaim() (*mcrypto.PrivateSpendKey, error) {
|
func (s *swapState) filterForClaim() (*mcrypto.PrivateSpendKey, error) {
|
||||||
logs, err := s.ETHClient().Raw().FilterLogs(s.ctx, eth.FilterQuery{
|
logs, err := s.ETHClient().Raw().FilterLogs(s.ctx, eth.FilterQuery{
|
||||||
Addresses: []ethcommon.Address{s.ContractAddr()},
|
Addresses: []ethcommon.Address{s.SwapCreatorAddr()},
|
||||||
Topics: [][]ethcommon.Hash{{claimedTopic}},
|
Topics: [][]ethcommon.Hash{{claimedTopic}},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ func lockXMRAndCheckForReadyLog(t *testing.T, s *swapState, xmrAddr *mcrypto.Add
|
|||||||
readyWatcher := watcher.NewEventFilter(
|
readyWatcher := watcher.NewEventFilter(
|
||||||
s.Backend.Ctx(),
|
s.Backend.Ctx(),
|
||||||
s.Backend.ETHClient().Raw(),
|
s.Backend.ETHClient().Raw(),
|
||||||
s.Backend.ContractAddr(),
|
s.Backend.SwapCreatorAddr(),
|
||||||
ethHeader.Number,
|
ethHeader.Number,
|
||||||
readyTopic,
|
readyTopic,
|
||||||
logReadyCh,
|
logReadyCh,
|
||||||
|
|||||||
@@ -66,8 +66,8 @@ func TestInstance_createOngoingSwap(t *testing.T) {
|
|||||||
rdb.EXPECT().GetCounterpartySwapPrivateKey(s.OfferID).Return(nil, errors.New("some error"))
|
rdb.EXPECT().GetCounterpartySwapPrivateKey(s.OfferID).Return(nil, errors.New("some error"))
|
||||||
rdb.EXPECT().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
rdb.EXPECT().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
||||||
StartNumber: big.NewInt(1),
|
StartNumber: big.NewInt(1),
|
||||||
ContractAddress: inst.backend.ContractAddr(),
|
SwapCreatorAddr: inst.backend.SwapCreatorAddr(),
|
||||||
Swap: &contracts.SwapFactorySwap{
|
Swap: &contracts.SwapCreatorSwap{
|
||||||
Timeout0: big.NewInt(1),
|
Timeout0: big.NewInt(1),
|
||||||
Timeout1: big.NewInt(2),
|
Timeout1: big.NewInt(2),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ func (s *swapState) handleSendKeysMessage(msg *message.SendKeysMessage) (common.
|
|||||||
go s.checkForXMRLock()
|
go s.checkForXMRLock()
|
||||||
|
|
||||||
out := &message.NotifyETHLocked{
|
out := &message.NotifyETHLocked{
|
||||||
Address: s.ContractAddr(),
|
Address: s.SwapCreatorAddr(),
|
||||||
TxHash: receipt.TxHash,
|
TxHash: receipt.TxHash,
|
||||||
ContractSwapID: s.contractSwapID,
|
ContractSwapID: s.contractSwapID,
|
||||||
ContractSwap: s.contractSwap,
|
ContractSwap: s.contractSwap,
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ type swapState struct {
|
|||||||
|
|
||||||
// swap contract and timeouts in it; set once contract is deployed
|
// swap contract and timeouts in it; set once contract is deployed
|
||||||
contractSwapID [32]byte
|
contractSwapID [32]byte
|
||||||
contractSwap *contracts.SwapFactorySwap
|
contractSwap *contracts.SwapCreatorSwap
|
||||||
t0, t1 time.Time
|
t0, t1 time.Time
|
||||||
|
|
||||||
// tracks the state of the swap
|
// tracks the state of the swap
|
||||||
@@ -182,8 +182,8 @@ func newSwapStateFromOngoing(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.ContractAddr() != ethSwapInfo.ContractAddress {
|
if b.SwapCreatorAddr() != ethSwapInfo.SwapCreatorAddr {
|
||||||
return nil, errContractAddrMismatch(ethSwapInfo.ContractAddress.String())
|
return nil, errContractAddrMismatch(ethSwapInfo.SwapCreatorAddr.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
s.setTimeouts(ethSwapInfo.Swap.Timeout0, ethSwapInfo.Swap.Timeout1)
|
s.setTimeouts(ethSwapInfo.Swap.Timeout0, ethSwapInfo.Swap.Timeout1)
|
||||||
@@ -244,7 +244,7 @@ func newSwapState(
|
|||||||
claimedWatcher := watcher.NewEventFilter(
|
claimedWatcher := watcher.NewEventFilter(
|
||||||
ctx,
|
ctx,
|
||||||
b.ETHClient().Raw(),
|
b.ETHClient().Raw(),
|
||||||
b.ContractAddr(),
|
b.SwapCreatorAddr(),
|
||||||
ethStartNumber,
|
ethStartNumber,
|
||||||
claimedTopic,
|
claimedTopic,
|
||||||
logClaimedCh,
|
logClaimedCh,
|
||||||
@@ -420,7 +420,7 @@ func (s *swapState) exit() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *swapState) tryRefund() (*ethtypes.Receipt, error) {
|
func (s *swapState) tryRefund() (*ethtypes.Receipt, error) {
|
||||||
stage, err := s.Contract().Swaps(s.ETHClient().CallOpts(s.ctx), s.contractSwapID)
|
stage, err := s.SwapCreator().Swaps(s.ETHClient().CallOpts(s.ctx), s.contractSwapID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -561,7 +561,7 @@ func (s *swapState) approveToken() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.Info("approving token for use by the swap contract...")
|
log.Info("approving token for use by the swap contract...")
|
||||||
_, err = s.sender.Approve(s.ContractAddr(), balance)
|
_, err = s.sender.Approve(s.SwapCreatorAddr(), balance)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to approve token: %w", err)
|
return fmt.Errorf("failed to approve token: %w", err)
|
||||||
}
|
}
|
||||||
@@ -639,7 +639,7 @@ func (s *swapState) lockAsset() (*ethtypes.Receipt, error) {
|
|||||||
s.fundsLocked = true
|
s.fundsLocked = true
|
||||||
s.setTimeouts(t0, t1)
|
s.setTimeouts(t0, t1)
|
||||||
|
|
||||||
s.contractSwap = &contracts.SwapFactorySwap{
|
s.contractSwap = &contracts.SwapCreatorSwap{
|
||||||
Owner: s.ETHClient().Address(),
|
Owner: s.ETHClient().Address(),
|
||||||
Claimer: s.xmrmakerAddress,
|
Claimer: s.xmrmakerAddress,
|
||||||
PubKeyClaim: cmtXMRMaker,
|
PubKeyClaim: cmtXMRMaker,
|
||||||
@@ -655,7 +655,7 @@ func (s *swapState) lockAsset() (*ethtypes.Receipt, error) {
|
|||||||
StartNumber: receipt.BlockNumber,
|
StartNumber: receipt.BlockNumber,
|
||||||
SwapID: s.contractSwapID,
|
SwapID: s.contractSwapID,
|
||||||
Swap: s.contractSwap,
|
Swap: s.contractSwap,
|
||||||
ContractAddress: s.Backend.ContractAddr(),
|
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.Backend.RecoveryDB().PutContractSwapInfo(s.OfferID(), ethInfo); err != nil {
|
if err := s.Backend.RecoveryDB().PutContractSwapInfo(s.OfferID(), ethInfo); err != nil {
|
||||||
@@ -670,7 +670,7 @@ func (s *swapState) lockAsset() (*ethtypes.Receipt, error) {
|
|||||||
// call Claim(). Ready() should only be called once XMRTaker sees XMRMaker lock his XMR.
|
// call Claim(). Ready() should only be called once XMRTaker sees XMRMaker lock his XMR.
|
||||||
// If time t_0 has passed, there is no point of calling Ready().
|
// If time t_0 has passed, there is no point of calling Ready().
|
||||||
func (s *swapState) ready() error {
|
func (s *swapState) ready() error {
|
||||||
stage, err := s.Contract().Swaps(s.ETHClient().CallOpts(s.ctx), s.contractSwapID)
|
stage, err := s.SwapCreator().Swaps(s.ETHClient().CallOpts(s.ctx), s.contractSwapID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ func TestSwapStateOngoing_handleEvent_EventXMRLocked(t *testing.T) {
|
|||||||
StartNumber: big.NewInt(int64(startNum)),
|
StartNumber: big.NewInt(int64(startNum)),
|
||||||
SwapID: s.contractSwapID,
|
SwapID: s.contractSwapID,
|
||||||
Swap: s.contractSwap,
|
Swap: s.contractSwap,
|
||||||
ContractAddress: s.Backend.ContractAddr(),
|
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||||
}
|
}
|
||||||
|
|
||||||
ss, err := newSwapStateFromOngoing(
|
ss, err := newSwapStateFromOngoing(
|
||||||
@@ -89,7 +89,7 @@ func TestSwapStateOngoing_handleEvent_EventETHClaimed(t *testing.T) {
|
|||||||
StartNumber: big.NewInt(int64(startNum)),
|
StartNumber: big.NewInt(int64(startNum)),
|
||||||
SwapID: s.contractSwapID,
|
SwapID: s.contractSwapID,
|
||||||
Swap: s.contractSwap,
|
Swap: s.contractSwap,
|
||||||
ContractAddress: s.Backend.ContractAddr(),
|
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||||
}
|
}
|
||||||
|
|
||||||
ss, err := newSwapStateFromOngoing(
|
ss, err := newSwapStateFromOngoing(
|
||||||
|
|||||||
@@ -90,8 +90,8 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
|||||||
txOpts, err := bind.NewKeyedTransactorWithChainID(pk, ec.ChainID())
|
txOpts, err := bind.NewKeyedTransactorWithChainID(pk, ec.ChainID())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
var forwarderAddress ethcommon.Address
|
var forwarderAddr ethcommon.Address
|
||||||
_, tx, _, err := contracts.DeploySwapFactory(txOpts, ec.Raw(), forwarderAddress)
|
_, tx, _, err := contracts.DeploySwapCreator(txOpts, ec.Raw(), forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
addr, err := bind.WaitDeployed(ctx, ec.Raw(), tx)
|
addr, err := bind.WaitDeployed(ctx, ec.Raw(), tx)
|
||||||
@@ -108,14 +108,14 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
|||||||
|
|
||||||
net := new(mockNet)
|
net := new(mockNet)
|
||||||
bcfg := &backend.Config{
|
bcfg := &backend.Config{
|
||||||
Ctx: context.Background(),
|
Ctx: ctx,
|
||||||
MoneroClient: monero.CreateWalletClient(t),
|
MoneroClient: monero.CreateWalletClient(t),
|
||||||
EthereumClient: ec,
|
EthereumClient: ec,
|
||||||
Environment: common.Development,
|
Environment: common.Development,
|
||||||
SwapManager: newSwapManager(t),
|
SwapManager: newSwapManager(t),
|
||||||
SwapFactoryAddress: addr,
|
SwapCreatorAddr: addr,
|
||||||
Net: net,
|
Net: net,
|
||||||
RecoveryDB: rdb,
|
RecoveryDB: rdb,
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := backend.NewBackend(bcfg)
|
b, err := backend.NewBackend(bcfg)
|
||||||
@@ -241,7 +241,7 @@ func TestSwapState_HandleProtocolMessage_SendKeysMessage_Refund(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check swap is marked completed
|
// check swap is marked completed
|
||||||
stage, err := s.Contract().Swaps(nil, s.contractSwapID)
|
stage, err := s.SwapCreator().Swaps(nil, s.contractSwapID)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, contracts.StageCompleted, stage)
|
require.Equal(t, contracts.StageCompleted, stage)
|
||||||
}
|
}
|
||||||
@@ -329,7 +329,7 @@ func TestSwapState_NotifyXMRLock_Refund(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check balance of contract is 0
|
// check balance of contract is 0
|
||||||
balance, err := s.ETHClient().Raw().BalanceAt(context.Background(), s.ContractAddr(), nil)
|
balance, err := s.ETHClient().Raw().BalanceAt(context.Background(), s.SwapCreatorAddr(), nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, uint64(0), balance.Uint64())
|
require.Equal(t, uint64(0), balance.Uint64())
|
||||||
}
|
}
|
||||||
@@ -429,7 +429,7 @@ func TestSwapState_ApproveToken(t *testing.T) {
|
|||||||
s, contract := newTestSwapStateWithERC20(t, initialBalance)
|
s, contract := newTestSwapStateWithERC20(t, initialBalance)
|
||||||
err := s.approveToken()
|
err := s.approveToken()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
allowance, err := contract.Allowance(&bind.CallOpts{}, s.ETHClient().Address(), s.ContractAddr())
|
allowance, err := contract.Allowance(&bind.CallOpts{}, s.ETHClient().Address(), s.SwapCreatorAddr())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, initialBalance, allowance)
|
require.Equal(t, initialBalance, allowance)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,9 +37,9 @@ func CreateRelayClaimRequest(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
claimerEthKey *ecdsa.PrivateKey,
|
claimerEthKey *ecdsa.PrivateKey,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
swapFactoryAddress ethcommon.Address,
|
swapCreatorAddr ethcommon.Address,
|
||||||
forwarderAddress ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret *[32]byte,
|
secret *[32]byte,
|
||||||
) (*message.RelayClaimRequest, error) {
|
) (*message.RelayClaimRequest, error) {
|
||||||
|
|
||||||
@@ -47,8 +47,8 @@ func CreateRelayClaimRequest(
|
|||||||
ctx,
|
ctx,
|
||||||
claimerEthKey,
|
claimerEthKey,
|
||||||
ec,
|
ec,
|
||||||
swapFactoryAddress,
|
swapCreatorAddr,
|
||||||
forwarderAddress,
|
forwarderAddr,
|
||||||
swap,
|
swap,
|
||||||
secret,
|
secret,
|
||||||
)
|
)
|
||||||
@@ -57,10 +57,10 @@ func CreateRelayClaimRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &message.RelayClaimRequest{
|
return &message.RelayClaimRequest{
|
||||||
OfferID: nil, // set elsewhere if sending to counterparty
|
OfferID: nil, // set elsewhere if sending to counterparty
|
||||||
SwapFactoryAddress: swapFactoryAddress,
|
SwapCreatorAddr: swapCreatorAddr,
|
||||||
Swap: swap,
|
Swap: swap,
|
||||||
Secret: secret[:],
|
Secret: secret[:],
|
||||||
Signature: signature,
|
Signature: signature,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,28 +22,28 @@ import (
|
|||||||
|
|
||||||
// Speed up tests a little by giving deployContracts(...) a package-level cache.
|
// Speed up tests a little by giving deployContracts(...) a package-level cache.
|
||||||
// These variables should not be accessed by other functions.
|
// These variables should not be accessed by other functions.
|
||||||
var _forwarderAddress *ethcommon.Address
|
var _forwarderAddr *ethcommon.Address
|
||||||
var _swapFactoryAddress *ethcommon.Address
|
var _swapCreatorAddr *ethcommon.Address
|
||||||
|
|
||||||
// deployContracts deploys and returns the swapFactory and forwarder addresses.
|
// deployContracts deploys and returns the swapCreator and forwarder addresses.
|
||||||
func deployContracts(t *testing.T, ec *ethclient.Client, key *ecdsa.PrivateKey) (ethcommon.Address, ethcommon.Address) {
|
func deployContracts(t *testing.T, ec *ethclient.Client, key *ecdsa.PrivateKey) (ethcommon.Address, ethcommon.Address) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
if _forwarderAddress == nil || _swapFactoryAddress == nil {
|
if _forwarderAddr == nil || _swapCreatorAddr == nil {
|
||||||
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, key)
|
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, key)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_forwarderAddress = &forwarderAddr
|
_forwarderAddr = &forwarderAddr
|
||||||
|
|
||||||
swapFactoryAddr, _, err := contracts.DeploySwapFactoryWithKey(ctx, ec, key, forwarderAddr)
|
swapCreatorAddr, _, err := contracts.DeploySwapCreatorWithKey(ctx, ec, key, forwarderAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_swapFactoryAddress = &swapFactoryAddr
|
_swapCreatorAddr = &swapCreatorAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
return *_swapFactoryAddress, *_forwarderAddress
|
return *_swapCreatorAddr, *_forwarderAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
func createTestSwap(claimer ethcommon.Address) *contracts.SwapFactorySwap {
|
func createTestSwap(claimer ethcommon.Address) *contracts.SwapCreatorSwap {
|
||||||
return &contracts.SwapFactorySwap{
|
return &contracts.SwapCreatorSwap{
|
||||||
Owner: ethcommon.Address{0x1},
|
Owner: ethcommon.Address{0x1},
|
||||||
Claimer: claimer,
|
Claimer: claimer,
|
||||||
PubKeyClaim: [32]byte{0x1},
|
PubKeyClaim: [32]byte{0x1},
|
||||||
@@ -62,16 +62,16 @@ func TestCreateRelayClaimRequest(t *testing.T) {
|
|||||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
secret := [32]byte{0x1}
|
secret := [32]byte{0x1}
|
||||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||||
|
|
||||||
// success path
|
// success path
|
||||||
swap := createTestSwap(claimer)
|
swap := createTestSwap(claimer)
|
||||||
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapFactoryAddr, forwarderAddr, swap, &secret)
|
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapCreatorAddr, forwarderAddr, swap, &secret)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NotNil(t, req)
|
require.NotNil(t, req)
|
||||||
|
|
||||||
// change the ethkey to not match the claimer address to trigger the error path
|
// change the ethkey to not match the claimer address to trigger the error path
|
||||||
ethKey = tests.GetTakerTestKey(t)
|
ethKey = tests.GetTakerTestKey(t)
|
||||||
_, err = CreateRelayClaimRequest(ctx, ethKey, ec, swapFactoryAddr, forwarderAddr, swap, &secret)
|
_, err = CreateRelayClaimRequest(ctx, ethKey, ec, swapCreatorAddr, forwarderAddr, swap, &secret)
|
||||||
require.ErrorContains(t, err, "signing key does not match claimer")
|
require.ErrorContains(t, err, "signing key does not match claimer")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ func createForwarderSignature(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
claimerEthKey *ecdsa.PrivateKey,
|
claimerEthKey *ecdsa.PrivateKey,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
swapFactoryAddress ethcommon.Address,
|
swapCreatorAddr ethcommon.Address,
|
||||||
forwarderAddress ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret *[32]byte,
|
secret *[32]byte,
|
||||||
) ([]byte, error) {
|
) ([]byte, error) {
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ func createForwarderSignature(
|
|||||||
return nil, fmt.Errorf("signing key does not match claimer %s", swap.Claimer)
|
return nil, fmt.Errorf("signing key does not match claimer %s", swap.Claimer)
|
||||||
}
|
}
|
||||||
|
|
||||||
forwarder, domainSeparator, err := getForwarderAndDomainSeparator(ctx, ec, forwarderAddress)
|
forwarder, domainSeparator, err := getForwarderAndDomainSeparator(ctx, ec, forwarderAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,7 @@ func createForwarderSignature(
|
|||||||
|
|
||||||
forwarderReq, err := createForwarderRequest(
|
forwarderReq, err := createForwarderRequest(
|
||||||
nonce,
|
nonce,
|
||||||
swapFactoryAddress,
|
swapCreatorAddr,
|
||||||
swap,
|
swap,
|
||||||
secret,
|
secret,
|
||||||
)
|
)
|
||||||
@@ -69,8 +69,8 @@ func createForwarderSignature(
|
|||||||
// createForwarderRequest creates the forwarder request, which we sign the digest of.
|
// createForwarderRequest creates the forwarder request, which we sign the digest of.
|
||||||
func createForwarderRequest(
|
func createForwarderRequest(
|
||||||
nonce *big.Int,
|
nonce *big.Int,
|
||||||
swapFactoryAddress ethcommon.Address,
|
swapCreatorAddr ethcommon.Address,
|
||||||
swap *contracts.SwapFactorySwap,
|
swap *contracts.SwapCreatorSwap,
|
||||||
secret *[32]byte,
|
secret *[32]byte,
|
||||||
) (*gsnforwarder.IForwarderForwardRequest, error) {
|
) (*gsnforwarder.IForwarderForwardRequest, error) {
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ func createForwarderRequest(
|
|||||||
|
|
||||||
req := &gsnforwarder.IForwarderForwardRequest{
|
req := &gsnforwarder.IForwarderForwardRequest{
|
||||||
From: swap.Claimer,
|
From: swap.Claimer,
|
||||||
To: swapFactoryAddress,
|
To: swapCreatorAddr,
|
||||||
Value: big.NewInt(0),
|
Value: big.NewInt(0),
|
||||||
Gas: big.NewInt(relayedClaimGas),
|
Gas: big.NewInt(relayedClaimGas),
|
||||||
Nonce: nonce,
|
Nonce: nonce,
|
||||||
@@ -93,28 +93,28 @@ func createForwarderRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getClaimRelayerTxCalldata returns the call data to be used when invoking the
|
// getClaimRelayerTxCalldata returns the call data to be used when invoking the
|
||||||
// claimRelayer method on the SwapFactory contract.
|
// claimRelayer method on the SwapCreator contract.
|
||||||
func getClaimRelayerTxCalldata(feeWei *big.Int, swap *contracts.SwapFactorySwap, secret *[32]byte) ([]byte, error) {
|
func getClaimRelayerTxCalldata(feeWei *big.Int, swap *contracts.SwapCreatorSwap, secret *[32]byte) ([]byte, error) {
|
||||||
return contracts.SwapFactoryParsedABI.Pack("claimRelayer", *swap, *secret, feeWei)
|
return contracts.SwapCreatorParsedABI.Pack("claimRelayer", *swap, *secret, feeWei)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getForwarderAndDomainSeparator(
|
func getForwarderAndDomainSeparator(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
forwarderAddress ethcommon.Address,
|
forwarderAddr ethcommon.Address,
|
||||||
) (*gsnforwarder.Forwarder, *[32]byte, error) {
|
) (*gsnforwarder.Forwarder, *[32]byte, error) {
|
||||||
chainID, err := ec.ChainID(ctx)
|
chainID, err := ec.ChainID(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
forwarder, err := gsnforwarder.NewForwarder(forwarderAddress, ec)
|
forwarder, err := gsnforwarder.NewForwarder(forwarderAddr, ec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
domainSeparator, err := rcommon.GetEIP712DomainSeparator(gsnforwarder.DefaultName,
|
domainSeparator, err := rcommon.GetEIP712DomainSeparator(gsnforwarder.DefaultName,
|
||||||
gsnforwarder.DefaultVersion, chainID, forwarderAddress)
|
gsnforwarder.DefaultVersion, chainID, forwarderAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("failed to get EIP712 domain separator: %w", err)
|
return nil, nil, fmt.Errorf("failed to get EIP712 domain separator: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ func ValidateAndSendTransaction(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
reqSwapFactory, err := contracts.NewSwapFactory(req.SwapFactoryAddress, ec.Raw())
|
reqSwapCreator, err := contracts.NewSwapCreator(req.SwapCreatorAddr, ec.Raw())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
reqForwarderAddr, err := reqSwapFactory.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
reqForwarderAddr, err := reqSwapCreator.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -56,7 +56,7 @@ func ValidateAndSendTransaction(
|
|||||||
// The size of request.Secret was vetted when it was deserialized
|
// The size of request.Secret was vetted when it was deserialized
|
||||||
secret := (*[32]byte)(req.Secret)
|
secret := (*[32]byte)(req.Secret)
|
||||||
|
|
||||||
forwarderReq, err := createForwarderRequest(nonce, req.SwapFactoryAddress, req.Swap, secret)
|
forwarderReq, err := createForwarderRequest(nonce, req.SwapCreatorAddr, req.Swap, secret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ func validateClaimRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// validateClaimValues validates the non-signature aspects of the claim request:
|
// validateClaimValues validates the non-signature aspects of the claim request:
|
||||||
// 1. the claim request's swap factory and forwarder contract bytecode matches ours
|
// 1. the claim request's swap creator and forwarder contract bytecode matches ours
|
||||||
// 2. the swap is for ETH and not an ERC20 token
|
// 2. the swap is for ETH and not an ERC20 token
|
||||||
// 3. the swap value is strictly greater than the relayer fee
|
// 3. the swap value is strictly greater than the relayer fee
|
||||||
// 4. TODO: Validate that the swap exists and is in a claimable state?
|
// 4. TODO: Validate that the swap exists and is in a claimable state?
|
||||||
@@ -41,19 +41,19 @@ func validateClaimValues(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
request *message.RelayClaimRequest,
|
request *message.RelayClaimRequest,
|
||||||
ec *ethclient.Client,
|
ec *ethclient.Client,
|
||||||
ourSwapFactoryAddr ethcommon.Address,
|
ourSwapCreatorAddr ethcommon.Address,
|
||||||
) error {
|
) error {
|
||||||
isTakerRelay := request.OfferID != nil
|
isTakerRelay := request.OfferID != nil
|
||||||
|
|
||||||
// Validate the deployed SwapFactory contract, if it is not at the same address
|
// Validate the deployed SwapCreator contract, if it is not at the same address
|
||||||
// as our own. The CheckSwapFactoryContractCode method validates both the
|
// as our own. The CheckSwapCreatorContractCode method validates both the
|
||||||
// SwapFactory bytecode and the Forwarder bytecode.
|
// SwapCreator bytecode and the Forwarder bytecode.
|
||||||
if request.SwapFactoryAddress != ourSwapFactoryAddr {
|
if request.SwapCreatorAddr != ourSwapCreatorAddr {
|
||||||
if isTakerRelay {
|
if isTakerRelay {
|
||||||
return fmt.Errorf("taker claim swap factory mismatch found=%s expected=%s",
|
return fmt.Errorf("taker claim swap creator mismatch found=%s expected=%s",
|
||||||
request.SwapFactoryAddress, ourSwapFactoryAddr)
|
request.SwapCreatorAddr, ourSwapCreatorAddr)
|
||||||
}
|
}
|
||||||
_, err := contracts.CheckSwapFactoryContractCode(ctx, ec, request.SwapFactoryAddress)
|
_, err := contracts.CheckSwapCreatorContractCode(ctx, ec, request.SwapCreatorAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -85,12 +85,12 @@ func validateClaimSignature(
|
|||||||
From: ethcommon.Address{0xFF}, // can be any value but zero, which will validate all signatures
|
From: ethcommon.Address{0xFF}, // can be any value but zero, which will validate all signatures
|
||||||
}
|
}
|
||||||
|
|
||||||
swapFactory, err := contracts.NewSwapFactory(request.SwapFactoryAddress, ec)
|
swapCreator, err := contracts.NewSwapCreator(request.SwapCreatorAddr, ec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
forwarderAddr, err := swapFactory.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
forwarderAddr, err := swapCreator.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -109,7 +109,7 @@ func validateClaimSignature(
|
|||||||
|
|
||||||
forwarderRequest, err := createForwarderRequest(
|
forwarderRequest, err := createForwarderRequest(
|
||||||
nonce,
|
nonce,
|
||||||
request.SwapFactoryAddress,
|
request.SwapCreatorAddr,
|
||||||
request.Swap,
|
request.Swap,
|
||||||
secret,
|
secret,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func TestValidateRelayerFee(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
key := tests.GetTakerTestKey(t)
|
key := tests.GetTakerTestKey(t)
|
||||||
swapFactoryAddr, _ := deployContracts(t, ec, key)
|
swapCreatorAddr, _ := deployContracts(t, ec, key)
|
||||||
|
|
||||||
type testCase struct {
|
type testCase struct {
|
||||||
description string
|
description string
|
||||||
@@ -50,7 +50,7 @@ func TestValidateRelayerFee(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range testCases {
|
for _, tc := range testCases {
|
||||||
swap := &contracts.SwapFactorySwap{
|
swap := &contracts.SwapCreatorSwap{
|
||||||
Owner: ethcommon.Address{},
|
Owner: ethcommon.Address{},
|
||||||
Claimer: ethcommon.Address{},
|
Claimer: ethcommon.Address{},
|
||||||
PubKeyClaim: [32]byte{},
|
PubKeyClaim: [32]byte{},
|
||||||
@@ -63,12 +63,12 @@ func TestValidateRelayerFee(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
request := &message.RelayClaimRequest{
|
request := &message.RelayClaimRequest{
|
||||||
SwapFactoryAddress: swapFactoryAddr,
|
SwapCreatorAddr: swapCreatorAddr,
|
||||||
Swap: swap,
|
Swap: swap,
|
||||||
Secret: make([]byte, 32),
|
Secret: make([]byte, 32),
|
||||||
}
|
}
|
||||||
|
|
||||||
err := validateClaimValues(ctx, request, ec, swapFactoryAddr)
|
err := validateClaimValues(ctx, request, ec, swapCreatorAddr)
|
||||||
if tc.expectErr != "" {
|
if tc.expectErr != "" {
|
||||||
require.ErrorContains(t, err, tc.expectErr, tc.description)
|
require.ErrorContains(t, err, tc.expectErr, tc.description)
|
||||||
} else {
|
} else {
|
||||||
@@ -82,18 +82,18 @@ func TestValidateRelayerFee(t *testing.T) {
|
|||||||
// the taker who is being asked to claim.
|
// the taker who is being asked to claim.
|
||||||
func Test_validateClaimValues_takerClaim_contractAddressNotEqualFail(t *testing.T) {
|
func Test_validateClaimValues_takerClaim_contractAddressNotEqualFail(t *testing.T) {
|
||||||
offerID := types.Hash{0x1} // non-nil offer ID passed to indicate taker claim
|
offerID := types.Hash{0x1} // non-nil offer ID passed to indicate taker claim
|
||||||
swapFactoryAddrInClaim := ethcommon.Address{0x1} // address in claim
|
swapCreatorAddrInClaim := ethcommon.Address{0x1} // address in claim
|
||||||
swapFactoryAddrOurs := ethcommon.Address{0x2} // passed to validateClaimValues
|
swapCreatorAddrOurs := ethcommon.Address{0x2} // passed to validateClaimValues
|
||||||
|
|
||||||
request := &message.RelayClaimRequest{
|
request := &message.RelayClaimRequest{
|
||||||
OfferID: &offerID,
|
OfferID: &offerID,
|
||||||
SwapFactoryAddress: swapFactoryAddrInClaim,
|
SwapCreatorAddr: swapCreatorAddrInClaim,
|
||||||
Secret: make([]byte, 32),
|
Secret: make([]byte, 32),
|
||||||
Swap: new(contracts.SwapFactorySwap), // test fails before we validate this
|
Swap: new(contracts.SwapCreatorSwap), // test fails before we validate this
|
||||||
}
|
}
|
||||||
|
|
||||||
err := validateClaimValues(context.Background(), request, nil, swapFactoryAddrOurs)
|
err := validateClaimValues(context.Background(), request, nil, swapCreatorAddrOurs)
|
||||||
require.ErrorContains(t, err, "taker claim swap factory mismatch")
|
require.ErrorContains(t, err, "taker claim swap creator mismatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
// When validating a claim made to a DHT advertised relayer, the contacts can have
|
// When validating a claim made to a DHT advertised relayer, the contacts can have
|
||||||
@@ -102,17 +102,17 @@ func Test_validateClaimValues_takerClaim_contractAddressNotEqualFail(t *testing.
|
|||||||
func Test_validateClaimValues_dhtClaim_contractAddressNotEqual(t *testing.T) {
|
func Test_validateClaimValues_dhtClaim_contractAddressNotEqual(t *testing.T) {
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
key := tests.GetTakerTestKey(t)
|
key := tests.GetTakerTestKey(t)
|
||||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, key)
|
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, key)
|
||||||
|
|
||||||
request := &message.RelayClaimRequest{
|
request := &message.RelayClaimRequest{
|
||||||
OfferID: nil, // DHT relayer claim
|
OfferID: nil, // DHT relayer claim
|
||||||
SwapFactoryAddress: forwarderAddr, // not a valid swap factory contract
|
SwapCreatorAddr: forwarderAddr, // not a valid swap creator contract
|
||||||
Secret: make([]byte, 32),
|
Secret: make([]byte, 32),
|
||||||
Swap: new(contracts.SwapFactorySwap), // test fails before we validate this
|
Swap: new(contracts.SwapCreatorSwap), // test fails before we validate this
|
||||||
}
|
}
|
||||||
|
|
||||||
err := validateClaimValues(context.Background(), request, ec, swapFactoryAddr)
|
err := validateClaimValues(context.Background(), request, ec, swapCreatorAddr)
|
||||||
require.ErrorContains(t, err, "contract address does not contain correct SwapFactory code")
|
require.ErrorContains(t, err, "contract address does not contain correct SwapCreator code")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_validateSignature(t *testing.T) {
|
func Test_validateSignature(t *testing.T) {
|
||||||
@@ -121,10 +121,10 @@ func Test_validateSignature(t *testing.T) {
|
|||||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
secret := [32]byte{0x1}
|
secret := [32]byte{0x1}
|
||||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||||
|
|
||||||
swap := createTestSwap(claimer)
|
swap := createTestSwap(claimer)
|
||||||
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapFactoryAddr, forwarderAddr, swap, &secret)
|
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapCreatorAddr, forwarderAddr, swap, &secret)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// success path
|
// success path
|
||||||
@@ -143,19 +143,19 @@ func Test_validateClaimRequest(t *testing.T) {
|
|||||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||||
ec, _ := tests.NewEthClient(t)
|
ec, _ := tests.NewEthClient(t)
|
||||||
secret := [32]byte{0x1}
|
secret := [32]byte{0x1}
|
||||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||||
|
|
||||||
swap := createTestSwap(claimer)
|
swap := createTestSwap(claimer)
|
||||||
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapFactoryAddr, forwarderAddr, swap, &secret)
|
req, err := CreateRelayClaimRequest(ctx, ethKey, ec, swapCreatorAddr, forwarderAddr, swap, &secret)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// success path
|
// success path
|
||||||
err = validateClaimRequest(ctx, req, ec, swapFactoryAddr)
|
err = validateClaimRequest(ctx, req, ec, swapCreatorAddr)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// test failure path by passing a non-eth asset
|
// test failure path by passing a non-eth asset
|
||||||
asset := ethcommon.Address{0x1}
|
asset := ethcommon.Address{0x1}
|
||||||
req.Swap.Asset = asset
|
req.Swap.Asset = asset
|
||||||
err = validateClaimRequest(ctx, req, ec, swapFactoryAddr)
|
err = validateClaimRequest(ctx, req, ec, swapCreatorAddr)
|
||||||
require.ErrorContains(t, err, fmt.Sprintf("relaying for ETH Asset %s is not supported", types.EthAsset(asset)))
|
require.ErrorContains(t, err, fmt.Sprintf("relaying for ETH Asset %s is not supported", types.EthAsset(asset)))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,6 +120,10 @@ func (s *Server) WsURL() string {
|
|||||||
|
|
||||||
// Start starts the JSON-RPC and Websocket server.
|
// Start starts the JSON-RPC and Websocket server.
|
||||||
func (s *Server) Start() error {
|
func (s *Server) Start() error {
|
||||||
|
if s.ctx.Err() != nil {
|
||||||
|
return s.ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
log.Infof("Starting RPC server on %s", s.HttpURL())
|
log.Infof("Starting RPC server on %s", s.HttpURL())
|
||||||
log.Infof("Starting websockets server on %s", s.WsURL())
|
log.Infof("Starting websockets server on %s", s.WsURL())
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ compile-contract() {
|
|||||||
--out "ethereum/${go_file_name}.go"
|
--out "ethereum/${go_file_name}.go"
|
||||||
}
|
}
|
||||||
|
|
||||||
compile-contract SwapFactory SwapFactory swap_factory
|
compile-contract SwapCreator SwapCreator swap_creator
|
||||||
compile-contract ERC20Mock ERC20Mock erc20_mock
|
compile-contract ERC20Mock ERC20Mock erc20_mock
|
||||||
compile-contract IERC20Metadata IERC20 ierc20
|
compile-contract IERC20Metadata IERC20 ierc20
|
||||||
compile-contract AggregatorV3Interface AggregatorV3Interface aggregator_v3_interface
|
compile-contract AggregatorV3Interface AggregatorV3Interface aggregator_v3_interface
|
||||||
|
|||||||
@@ -106,9 +106,9 @@ start-daemons() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
SWAP_FACTORY_ADDR="$(jq -r .swapFactory "${CONTRACT_ADDR_FILE}")"
|
SWAP_CREATOR_ADDR="$(jq -r .swapCreatorAddr "${CONTRACT_ADDR_FILE}")"
|
||||||
FORWARDER_ADDR="$(jq -r .forwarder "${CONTRACT_ADDR_FILE}")"
|
FORWARDER_ADDR="$(jq -r .forwarderAddr "${CONTRACT_ADDR_FILE}")"
|
||||||
if [[ -z "${SWAP_FACTORY_ADDR}" ]] || [[ -z "${FORWARDER_ADDR}" ]]; then
|
if [[ -z "${SWAP_CREATOR_ADDR}" ]] || [[ -z "${FORWARDER_ADDR}" ]]; then
|
||||||
echo "Failed to get Alice's deployed contract addresses"
|
echo "Failed to get Alice's deployed contract addresses"
|
||||||
stop-daemons
|
stop-daemons
|
||||||
exit 1
|
exit 1
|
||||||
@@ -120,14 +120,14 @@ start-daemons() {
|
|||||||
"--data-dir=${SWAP_TEST_DATA_DIR}/bob" \
|
"--data-dir=${SWAP_TEST_DATA_DIR}/bob" \
|
||||||
--libp2p-port=9944 \
|
--libp2p-port=9944 \
|
||||||
"--bootnodes=${ALICE_MULTIADDR}" \
|
"--bootnodes=${ALICE_MULTIADDR}" \
|
||||||
"--contract-address=${SWAP_FACTORY_ADDR}"
|
"--contract-address=${SWAP_CREATOR_ADDR}"
|
||||||
|
|
||||||
start-swapd charlie "${CHARLIE_RPC_PORT}" \
|
start-swapd charlie "${CHARLIE_RPC_PORT}" \
|
||||||
"--log-level=${LOG_LEVEL}" \
|
"--log-level=${LOG_LEVEL}" \
|
||||||
--data-dir "${SWAP_TEST_DATA_DIR}/charlie" \
|
--data-dir "${SWAP_TEST_DATA_DIR}/charlie" \
|
||||||
--libp2p-port=9955 \
|
--libp2p-port=9955 \
|
||||||
"--bootnodes=${ALICE_MULTIADDR}" \
|
"--bootnodes=${ALICE_MULTIADDR}" \
|
||||||
"--contract-address=${SWAP_FACTORY_ADDR}" \
|
"--contract-address=${SWAP_CREATOR_ADDR}" \
|
||||||
"--relayer"
|
"--relayer"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +143,7 @@ stop-daemons() {
|
|||||||
echo "running integration tests..."
|
echo "running integration tests..."
|
||||||
create-eth-keys
|
create-eth-keys
|
||||||
start-daemons
|
start-daemons
|
||||||
TESTS=integration CONTRACT_ADDR=${SWAP_FACTORY_ADDR} go test ./tests -v -count=1 -timeout=30m
|
TESTS=integration CONTRACT_ADDR=${SWAP_CREATOR_ADDR} go test ./tests -v -count=1 -timeout=30m
|
||||||
OK="${?}"
|
OK="${?}"
|
||||||
KEEP_TEST_DATA="${OK}" stop-daemons
|
KEEP_TEST_DATA="${OK}" stop-daemons
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user