mirror of
https://github.com/AthanorLabs/atomic-swap.git
synced 2026-01-07 21:34:05 -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
|
||||
env:
|
||||
ETH_MAINNET_ENDPOINT: ${{ secrets.ETH_MAINNET_ENDPOINT }}
|
||||
ETH_SEPOLIA_ENDPOINT: ${{ secrets.ETH_SEPOLIA_ENDPOINT }}
|
||||
run: ./scripts/run-unit-tests.sh
|
||||
|
||||
- name: Upload code coverage
|
||||
|
||||
@@ -30,87 +30,87 @@ var (
|
||||
)
|
||||
|
||||
type contractAddresses struct {
|
||||
SwapFactory ethcommon.Address `json:"swapFactory" validate:"required"`
|
||||
Forwarder ethcommon.Address `json:"forwarder" validate:"required"`
|
||||
SwapCreatorAddr ethcommon.Address `json:"swapCreatorAddr" validate:"required"`
|
||||
ForwarderAddr ethcommon.Address `json:"forwarderAddr" validate:"required"`
|
||||
}
|
||||
|
||||
func getOrDeploySwapFactory(
|
||||
func getOrDeploySwapCreator(
|
||||
ctx context.Context,
|
||||
address ethcommon.Address,
|
||||
swapCreatorAddr ethcommon.Address,
|
||||
env common.Environment,
|
||||
dataDir string,
|
||||
ec extethclient.EthClient,
|
||||
forwarderAddress ethcommon.Address,
|
||||
forwarderAddr ethcommon.Address,
|
||||
) (ethcommon.Address, 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,
|
||||
// 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 {
|
||||
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 {
|
||||
// otherwise, load the contract from the given address
|
||||
// and check that its bytecode is valid (ie. matches the
|
||||
// bytecode of this repo's swap contract)
|
||||
_, err = contracts.CheckSwapFactoryContractCode(ctx, ec.Raw(), address)
|
||||
_, err = contracts.CheckSwapCreatorContractCode(ctx, ec.Raw(), swapCreatorAddr)
|
||||
if err != nil {
|
||||
return ethcommon.Address{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return address, nil
|
||||
return swapCreatorAddr, nil
|
||||
}
|
||||
|
||||
func deploySwapFactory(
|
||||
func deploySwapCreator(
|
||||
ctx context.Context,
|
||||
ec *ethclient.Client,
|
||||
privkey *ecdsa.PrivateKey,
|
||||
forwarderAddress ethcommon.Address,
|
||||
forwarderAddr ethcommon.Address,
|
||||
dataDir string,
|
||||
) (ethcommon.Address, *contracts.SwapFactory, error) {
|
||||
) (ethcommon.Address, *contracts.SwapCreator, error) {
|
||||
|
||||
if privkey == nil {
|
||||
return ethcommon.Address{}, nil, errNoEthereumPrivateKey
|
||||
}
|
||||
|
||||
if (forwarderAddress == ethcommon.Address{}) {
|
||||
if (forwarderAddr == ethcommon.Address{}) {
|
||||
// deploy forwarder contract as well
|
||||
var err error
|
||||
forwarderAddress, err = contracts.DeployGSNForwarderWithKey(ctx, ec, privkey)
|
||||
forwarderAddr, err = contracts.DeployGSNForwarderWithKey(ctx, ec, privkey)
|
||||
if err != nil {
|
||||
return ethcommon.Address{}, nil, err
|
||||
}
|
||||
} else {
|
||||
if err := contracts.CheckForwarderContractCode(ctx, ec, forwarderAddress); err != nil {
|
||||
if err := contracts.CheckForwarderContractCode(ctx, ec, forwarderAddr); err != nil {
|
||||
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 {
|
||||
return ethcommon.Address{}, nil, err
|
||||
}
|
||||
|
||||
// store the contract address on disk
|
||||
err = writeContractAddressToFile(
|
||||
// store the contract addresses on disk
|
||||
err = writeContractAddressesToFile(
|
||||
path.Join(dataDir, contractAddressesFile),
|
||||
&contractAddresses{
|
||||
SwapFactory: swapFactoryAddress,
|
||||
Forwarder: forwarderAddress,
|
||||
SwapCreatorAddr: swapCreatorAddr,
|
||||
ForwarderAddr: forwarderAddr,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
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
|
||||
func writeContractAddressToFile(filePath string, addresses *contractAddresses) error {
|
||||
// writeContractAddressesToFile writes the contract addresses to the given file
|
||||
func writeContractAddressesToFile(filePath string, addresses *contractAddresses) error {
|
||||
jsonData, err := vjson.MarshalIndentStruct(addresses, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
||||
func TestGetOrDeploySwapCreator_DeployNoForwarder(t *testing.T) {
|
||||
pk := tests.GetTakerTestKey(t)
|
||||
ec := extethclient.CreateTestClient(t, pk)
|
||||
tmpDir := t.TempDir()
|
||||
@@ -24,7 +24,7 @@ func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
||||
forwarder, err := contracts.DeployGSNForwarderWithKey(context.Background(), ec.Raw(), pk)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = getOrDeploySwapFactory(
|
||||
_, err = getOrDeploySwapCreator(
|
||||
context.Background(),
|
||||
ethcommon.Address{},
|
||||
common.Development,
|
||||
@@ -35,12 +35,12 @@ func TestGetOrDeploySwapFactory_DeployNoForwarder(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestGetOrDeploySwapFactory_DeployForwarderAlso(t *testing.T) {
|
||||
func TestGetOrDeploySwapCreator_DeployForwarderAlso(t *testing.T) {
|
||||
pk := tests.GetTakerTestKey(t)
|
||||
ec := extethclient.CreateTestClient(t, pk)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
_, err := getOrDeploySwapFactory(
|
||||
_, err := getOrDeploySwapCreator(
|
||||
context.Background(),
|
||||
ethcommon.Address{},
|
||||
common.Development,
|
||||
@@ -51,7 +51,7 @@ func TestGetOrDeploySwapFactory_DeployForwarderAlso(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
||||
func TestGetOrDeploySwapCreator_Get(t *testing.T) {
|
||||
pk := tests.GetTakerTestKey(t)
|
||||
ec := extethclient.CreateTestClient(t, pk)
|
||||
tmpDir := t.TempDir()
|
||||
@@ -61,7 +61,7 @@ func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
||||
t.Log(forwarder)
|
||||
|
||||
// deploy and get address
|
||||
address, err := getOrDeploySwapFactory(
|
||||
address, err := getOrDeploySwapCreator(
|
||||
context.Background(),
|
||||
ethcommon.Address{},
|
||||
common.Development,
|
||||
@@ -71,7 +71,7 @@ func TestGetOrDeploySwapFactory_Get(t *testing.T) {
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
addr2, err := getOrDeploySwapFactory(
|
||||
addr2, err := getOrDeploySwapCreator(
|
||||
context.Background(),
|
||||
address,
|
||||
common.Development,
|
||||
|
||||
@@ -151,7 +151,7 @@ func cliApp() *cli.App {
|
||||
},
|
||||
&cli.StringFlag{
|
||||
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{
|
||||
Name: flagBootnodes,
|
||||
@@ -362,17 +362,17 @@ func getEnvConfig(c *cli.Context, devXMRMaker bool, devXMRTaker bool) (*common.C
|
||||
return nil, errFlagsMutuallyExclusive(flagDeploy, flagContractAddress)
|
||||
}
|
||||
// Zero out the contract address, we'll set its final value after deploying
|
||||
conf.SwapFactoryAddress = ethcommon.Address{}
|
||||
conf.SwapCreatorAddr = ethcommon.Address{}
|
||||
} else {
|
||||
contractAddrStr := c.String(flagContractAddress)
|
||||
if contractAddrStr != "" {
|
||||
if !ethcommon.IsHexAddress(contractAddrStr) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -380,42 +380,44 @@ func getEnvConfig(c *cli.Context, devXMRMaker bool, devXMRTaker bool) (*common.C
|
||||
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
|
||||
// contract.
|
||||
func validateOrDeployContracts(c *cli.Context, envConf *common.Config, ec extethclient.EthClient) error {
|
||||
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")
|
||||
}
|
||||
|
||||
// forwarderAddress is set only if we're deploying the swap contract, and the --forwarder-address
|
||||
// flag is set. otherwise, if we're deploying and the flag isn't set, we also deploy the forwarder.
|
||||
var forwarderAddress ethcommon.Address
|
||||
forwarderAddressStr := c.String(flagForwarderAddress)
|
||||
if deploy && forwarderAddressStr != "" {
|
||||
if !ethcommon.IsHexAddress(forwarderAddressStr) {
|
||||
// forwarderAddr is set only if we're deploying the swap creator contract
|
||||
// and the --forwarder-address flag is set. Otherwise, if we're deploying
|
||||
// and this flag isn't set, we deploy both the forwarder and the swap
|
||||
// creator contracts.
|
||||
var forwarderAddr ethcommon.Address
|
||||
forwarderAddrStr := c.String(flagForwarderAddress)
|
||||
if deploy && forwarderAddrStr != "" {
|
||||
if !ethcommon.IsHexAddress(forwarderAddrStr) {
|
||||
return fmt.Errorf("%q requires a valid ethereum address", flagForwarderAddress)
|
||||
}
|
||||
|
||||
forwarderAddress = ethcommon.HexToAddress(forwarderAddressStr)
|
||||
} else if !deploy && forwarderAddressStr != "" {
|
||||
forwarderAddr = ethcommon.HexToAddress(forwarderAddrStr)
|
||||
} else if !deploy && forwarderAddrStr != "" {
|
||||
return fmt.Errorf("using flag %q requires the %q flag", flagForwarderAddress, flagDeploy)
|
||||
}
|
||||
|
||||
contractAddr, err := getOrDeploySwapFactory(
|
||||
swapCreatorAddr, err := getOrDeploySwapCreator(
|
||||
c.Context,
|
||||
envConf.SwapFactoryAddress,
|
||||
envConf.SwapCreatorAddr,
|
||||
envConf.Env,
|
||||
envConf.DataDir,
|
||||
ec,
|
||||
forwarderAddress,
|
||||
forwarderAddr,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
envConf.SwapFactoryAddress = contractAddr
|
||||
envConf.SwapCreatorAddr = swapCreatorAddr
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -96,19 +96,19 @@ func TestDaemon_DevXMRTaker(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
m := make(map[string]string)
|
||||
require.NoError(t, json.Unmarshal(data, &m))
|
||||
swapFactoryAddr, ok := m["swapFactory"]
|
||||
swapCreatorAddr, ok := m["swapCreatorAddr"]
|
||||
require.True(t, ok)
|
||||
forwarderAddr, ok := m["forwarder"]
|
||||
forwarderAddr, ok := m["forwarderAddr"]
|
||||
require.True(t, ok)
|
||||
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
ecCtx := context.Background()
|
||||
discoveredForwarderAddr, err :=
|
||||
contracts.CheckSwapFactoryContractCode(ecCtx, ec, ethcommon.HexToAddress(swapFactoryAddr))
|
||||
contracts.CheckSwapCreatorContractCode(ecCtx, ec, ethcommon.HexToAddress(swapCreatorAddr))
|
||||
require.NoError(t, err)
|
||||
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
|
||||
err = contracts.CheckForwarderContractCode(ecCtx, ec, ethcommon.HexToAddress(forwarderAddr))
|
||||
require.NoError(t, err)
|
||||
@@ -120,7 +120,7 @@ func TestDaemon_DevXMRMaker(t *testing.T) {
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
|
||||
// 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)
|
||||
|
||||
flags := []string{
|
||||
@@ -128,7 +128,7 @@ func TestDaemon_DevXMRMaker(t *testing.T) {
|
||||
fmt.Sprintf("--%s", flagDevXMRMaker),
|
||||
fmt.Sprintf("--%s=dev", flagEnv),
|
||||
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=%d", flagRPCPort, rpcPort),
|
||||
fmt.Sprintf("--%s=0", flagLibp2pPort),
|
||||
@@ -157,9 +157,9 @@ func TestDaemon_BadFlags(t *testing.T) {
|
||||
ec, _ := tests.NewEthClient(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)
|
||||
forwarderAddr, err := swapFactory.TrustedForwarder(nil)
|
||||
forwarderAddr, err := swapCreator.TrustedForwarder(nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
baseFlags := []string{
|
||||
@@ -184,10 +184,10 @@ func TestDaemon_BadFlags(t *testing.T) {
|
||||
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{
|
||||
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",
|
||||
},
|
||||
@@ -204,19 +204,19 @@ func TestDaemon_BadFlags(t *testing.T) {
|
||||
extraFlags: []string{
|
||||
fmt.Sprintf("--%s=%s", flagForwarderAddress, forwarderAddr),
|
||||
// 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),
|
||||
},
|
||||
{
|
||||
description: "pass invalid SwapFactory contract",
|
||||
description: "pass invalid SwapCreator contract",
|
||||
extraFlags: []string{
|
||||
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{
|
||||
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
|
||||
description: "forgot to prefix the flag name with dashes",
|
||||
extraFlags: []string{
|
||||
flagContractAddress, swapFactoryAddr.String(),
|
||||
flagContractAddress, swapCreatorAddr.String(),
|
||||
},
|
||||
expectErr: fmt.Sprintf("unknown command %q", flagContractAddress),
|
||||
},
|
||||
|
||||
@@ -13,7 +13,7 @@ coverage:
|
||||
# Don't calculate code coverage percentages on generated abigen files
|
||||
# or our profiling code
|
||||
ignore:
|
||||
- ethereum/swap_factory.go
|
||||
- ethereum/swap_creator.go
|
||||
- ethereum/aggregator_v3_interface.go
|
||||
- ethereum/erc20_mock.go
|
||||
- ethereum/ierc20.go
|
||||
|
||||
@@ -33,12 +33,12 @@ type MoneroNode struct {
|
||||
|
||||
// Config contains constants that are defaults for various environments
|
||||
type Config struct {
|
||||
Env Environment
|
||||
DataDir string
|
||||
MoneroNodes []*MoneroNode
|
||||
SwapFactoryAddress ethcommon.Address
|
||||
ForwarderContractAddress ethcommon.Address
|
||||
Bootnodes []string
|
||||
Env Environment
|
||||
DataDir string
|
||||
MoneroNodes []*MoneroNode
|
||||
SwapCreatorAddr ethcommon.Address
|
||||
ForwarderAddr ethcommon.Address
|
||||
Bootnodes []string
|
||||
}
|
||||
|
||||
// MainnetConfig is the mainnet ethereum and monero configuration
|
||||
@@ -86,8 +86,8 @@ func StagenetConfig() *Config {
|
||||
Port: 38081,
|
||||
},
|
||||
},
|
||||
SwapFactoryAddress: ethcommon.HexToAddress("0x531BAAceB7939C04ef0DE517557a2f84F5545EFB"),
|
||||
ForwarderContractAddress: ethcommon.HexToAddress("0x8730e444bB1501C23BC3E170405a8EbAFD138000"),
|
||||
SwapCreatorAddr: ethcommon.HexToAddress("0x2C3b31E4379ab5B1B0Cb12B37D2B268FEf44d7f0"),
|
||||
ForwarderAddr: ethcommon.HexToAddress("0xF45e206B38f5901daBf9758fcC2CFce6aEe5B134"),
|
||||
Bootnodes: []string{
|
||||
"/ip4/134.122.115.208/tcp/9900/p2p/12D3KooWDqCzbjexHEa8Rut7bzxHFpRMZyDRW1L6TGkL1KY24JH5",
|
||||
"/ip4/143.198.123.27/tcp/9900/p2p/12D3KooWSc4yFkPWBFmPToTMbhChH3FAgGH96DNzSg5fio1pQYoN",
|
||||
|
||||
@@ -25,7 +25,7 @@ const (
|
||||
TimeFmtNSecs = "2006-01-02-15:04:05.999999999"
|
||||
)
|
||||
|
||||
// SwapFactory.sol event signatures
|
||||
// SwapCreator.sol event signatures
|
||||
const (
|
||||
ReadyEventSignature = "Ready(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)
|
||||
}
|
||||
|
||||
if conf.EnvConf.SwapFactoryAddress == (ethcommon.Address{}) {
|
||||
panic("swap factory address not specified")
|
||||
if conf.EnvConf.SwapCreatorAddr == (ethcommon.Address{}) {
|
||||
panic("swap creator address not specified")
|
||||
}
|
||||
|
||||
ec := conf.EthereumClient
|
||||
@@ -105,14 +105,14 @@ func RunSwapDaemon(ctx context.Context, conf *SwapdConfig) (err error) {
|
||||
}()
|
||||
|
||||
swapBackend, err := backend.NewBackend(&backend.Config{
|
||||
Ctx: ctx,
|
||||
MoneroClient: conf.MoneroClient,
|
||||
EthereumClient: conf.EthereumClient,
|
||||
Environment: conf.EnvConf.Env,
|
||||
SwapFactoryAddress: conf.EnvConf.SwapFactoryAddress,
|
||||
SwapManager: sm,
|
||||
RecoveryDB: sdb.RecoveryDB(),
|
||||
Net: host,
|
||||
Ctx: ctx,
|
||||
MoneroClient: conf.MoneroClient,
|
||||
EthereumClient: conf.EthereumClient,
|
||||
Environment: conf.EnvConf.Env,
|
||||
SwapCreatorAddr: conf.EnvConf.SwapCreatorAddr,
|
||||
SwapManager: sm,
|
||||
RecoveryDB: sdb.RecoveryDB(),
|
||||
Net: host,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to make backend: %w", err)
|
||||
|
||||
@@ -62,11 +62,11 @@ func init() {
|
||||
_ = logging.SetLogLevel("xmrtaker", level)
|
||||
}
|
||||
|
||||
var _swapFactoryAddress *ethcommon.Address
|
||||
var _swapCreatorAddr *ethcommon.Address
|
||||
|
||||
func getSwapFactoryAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address {
|
||||
if _swapFactoryAddress != nil {
|
||||
return *_swapFactoryAddress
|
||||
func getSwapCreatorAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address {
|
||||
if _swapCreatorAddr != nil {
|
||||
return *_swapCreatorAddr
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
@@ -75,11 +75,11 @@ func getSwapFactoryAddress(t *testing.T, ec *ethclient.Client) ethcommon.Address
|
||||
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, ethKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
swapFactoryAddr, _, err := contracts.DeploySwapFactoryWithKey(ctx, ec, ethKey, forwarderAddr)
|
||||
swapCreatorAddr, _, err := contracts.DeploySwapCreatorWithKey(ctx, ec, ethKey, forwarderAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
_swapFactoryAddress = &swapFactoryAddr
|
||||
return swapFactoryAddr
|
||||
_swapCreatorAddr = &swapCreatorAddr
|
||||
return swapCreatorAddr
|
||||
}
|
||||
|
||||
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 = *common.ConfigDefaultsForEnv(common.Development)
|
||||
envConf.DataDir = t.TempDir()
|
||||
envConf.SwapFactoryAddress = getSwapFactoryAddress(t, ec.Raw())
|
||||
envConf.SwapCreatorAddr = getSwapCreatorAddress(t, ec.Raw())
|
||||
|
||||
return &SwapdConfig{
|
||||
EnvConf: envConf,
|
||||
@@ -227,7 +227,7 @@ func TestRunSwapDaemon_SwapBobHasNoEth_AliceRelaysClaim(t *testing.T) {
|
||||
|
||||
aliceConf := createTestConf(t, tests.GetTakerTestKey(t))
|
||||
|
||||
timeout := 5 * time.Minute
|
||||
timeout := 7 * time.Minute
|
||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
||||
|
||||
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)
|
||||
minimumFundAlice(t, aliceConf.EthereumClient, providesAmt)
|
||||
|
||||
timeout := 7 * time.Minute
|
||||
timeout := 8 * time.Minute
|
||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf)
|
||||
|
||||
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())
|
||||
require.NoError(t, err)
|
||||
|
||||
timeout := 5 * time.Minute
|
||||
timeout := 7 * time.Minute
|
||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
||||
|
||||
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.IsRelayer = true
|
||||
|
||||
timeout := 5 * time.Minute
|
||||
timeout := 7 * time.Minute
|
||||
ctx := launchDaemons(t, timeout, bobConf, aliceConf, charlieConf)
|
||||
|
||||
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
|
||||
// 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.
|
||||
func (db *RecoveryDB) PutContractSwapInfo(id types.Hash, info *EthereumSwapInfo) error {
|
||||
val, err := vjson.MarshalStruct(info)
|
||||
@@ -91,7 +91,7 @@ func (db *RecoveryDB) PutContractSwapInfo(id types.Hash, info *EthereumSwapInfo)
|
||||
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.
|
||||
func (db *RecoveryDB) GetContractSwapInfo(id types.Hash) (*EthereumSwapInfo, error) {
|
||||
key := getRecoveryDBKey(id, contractSwapInfoPrefix)
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
||||
si := &EthereumSwapInfo{
|
||||
StartNumber: big.NewInt(12345),
|
||||
SwapID: types.Hash{1, 2, 3, 4},
|
||||
Swap: &contracts.SwapFactorySwap{
|
||||
Swap: &contracts.SwapCreatorSwap{
|
||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||
@@ -48,7 +48,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
||||
Value: big.NewInt(9876),
|
||||
Nonce: big.NewInt(1234),
|
||||
},
|
||||
ContractAddress: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||
SwapCreatorAddr: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||
}
|
||||
|
||||
expectedStr := `{
|
||||
@@ -65,7 +65,7 @@ func TestRecoveryDB_ContractSwapInfo(t *testing.T) {
|
||||
"value": 9876,
|
||||
"nonce": 1234
|
||||
},
|
||||
"contractAddress": "0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"
|
||||
"swapCreatorAddr": "0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"
|
||||
}`
|
||||
jsonData, err := vjson.MarshalStruct(si)
|
||||
require.NoError(t, err)
|
||||
@@ -151,7 +151,7 @@ func TestRecoveryDB_DeleteSwap(t *testing.T) {
|
||||
si := &EthereumSwapInfo{
|
||||
StartNumber: big.NewInt(12345),
|
||||
SwapID: types.Hash{1, 2, 3, 4},
|
||||
Swap: &contracts.SwapFactorySwap{
|
||||
Swap: &contracts.SwapCreatorSwap{
|
||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||
@@ -162,7 +162,7 @@ func TestRecoveryDB_DeleteSwap(t *testing.T) {
|
||||
Value: big.NewInt(9876),
|
||||
Nonce: big.NewInt(1234),
|
||||
},
|
||||
ContractAddress: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||
SwapCreatorAddr: ethcommon.HexToAddress("0xd2b5d6252d0645e4cf4bb547e82a485f527befb7"),
|
||||
}
|
||||
|
||||
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
|
||||
// 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"`
|
||||
|
||||
// Swap is the `Swap` structure inside SwapFactory.sol.
|
||||
Swap *contracts.SwapFactorySwap `json:"swap" validate:"required"`
|
||||
// Swap is the `Swap` structure inside SwapCreator.sol.
|
||||
Swap *contracts.SwapCreatorSwap `json:"swap" validate:"required"`
|
||||
|
||||
// ContractAddress is the address of the contract on which the swap was created.
|
||||
ContractAddress ethcommon.Address `json:"contractAddress" validate:"required"`
|
||||
// SwapCreatorAddr is the address of the contract on which the swap was created.
|
||||
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
|
||||
`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
|
||||
# 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
|
||||
$ ./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
|
||||
@@ -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
|
||||
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
|
||||
`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
|
||||
variable like this:
|
||||
```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:
|
||||
@@ -220,4 +220,4 @@ To query information for a past swap using its ID, you can run:
|
||||
./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/).
|
||||
|
||||
> 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
|
||||
deployed with `--deploy` in subsequent `swapd` instances, use the flag
|
||||
`--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.
|
||||
// This file is a generated binding and any manual changes will be lost.
|
||||
|
||||
@@ -29,6 +26,7 @@ var (
|
||||
_ = common.Big1
|
||||
_ = types.BloomLookup
|
||||
_ = event.NewSubscription
|
||||
_ = abi.ConvertType
|
||||
)
|
||||
|
||||
// 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.
|
||||
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 {
|
||||
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
|
||||
|
||||
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}" --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
|
||||
|
||||
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.
|
||||
// This file is a generated binding and any manual changes will be lost.
|
||||
|
||||
@@ -29,12 +26,13 @@ var (
|
||||
_ = common.Big1
|
||||
_ = types.BloomLookup
|
||||
_ = event.NewSubscription
|
||||
_ = abi.ConvertType
|
||||
)
|
||||
|
||||
// UTContractMetaData contains all meta data concerning the UTContract contract.
|
||||
var UTContractMetaData = &bind.MetaData{
|
||||
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.
|
||||
@@ -159,11 +157,11 @@ func NewUTContractFilterer(address common.Address, filterer bind.ContractFiltere
|
||||
|
||||
// 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) {
|
||||
parsed, err := abi.JSON(strings.NewReader(UTContractABI))
|
||||
parsed, err := UTContractMetaData.GetAbi()
|
||||
if err != nil {
|
||||
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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -20,7 +20,7 @@ import (
|
||||
"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
|
||||
func deployContract(
|
||||
t *testing.T,
|
||||
@@ -29,7 +29,7 @@ func deployContract(
|
||||
trustedForwarder ethcommon.Address,
|
||||
) ethcommon.Address {
|
||||
ctx := context.Background()
|
||||
contractAddr, _, err := DeploySwapFactoryWithKey(ctx, ec, pk, trustedForwarder)
|
||||
contractAddr, _, err := DeploySwapCreatorWithKey(ctx, ec, pk, trustedForwarder)
|
||||
require.NoError(t, err)
|
||||
return contractAddr
|
||||
}
|
||||
@@ -40,7 +40,7 @@ func deployForwarder(t *testing.T, ec *ethclient.Client, pk *ecdsa.PrivateKey) e
|
||||
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.
|
||||
func getContractCode(t *testing.T, trustedForwarder ethcommon.Address) []byte {
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
@@ -59,20 +59,20 @@ func TestCheckForwarderContractCode(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// This test will fail if the compiled SwapFactory contract is updated, but the
|
||||
// expectedSwapFactoryBytecodeHex constant is not updated. Use this test to update the
|
||||
// This test will fail if the compiled SwapCreator contract is updated, but the
|
||||
// expectedSwapCreatorBytecodeHex constant is not updated. Use this test to update the
|
||||
// constant.
|
||||
func TestExpectedSwapFactoryBytecodeHex(t *testing.T) {
|
||||
func TestExpectedSwapCreatorBytecodeHex(t *testing.T) {
|
||||
allZeroTrustedForwarder := ethcommon.Address{}
|
||||
codeHex := ethcommon.Bytes2Hex(getContractCode(t, allZeroTrustedForwarder))
|
||||
require.Equal(t, expectedSwapFactoryBytecodeHex, codeHex,
|
||||
"update the expectedSwapFactoryBytecodeHex constant with the actual value to fix this test")
|
||||
require.Equal(t, expectedSwapCreatorBytecodeHex, codeHex,
|
||||
"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
|
||||
// forwarderAddressIndexes slice of trusted forwarder locations is not updated. Use this
|
||||
// test to update the slice.
|
||||
func TestForwarderAddressIndexes(t *testing.T) {
|
||||
// This test will fail if the compiled SwapCreator contract is updated, but the
|
||||
// forwarderAddrIndexes slice of trusted forwarder locations is not updated. Use
|
||||
// this test to update the slice.
|
||||
func TestForwarderAddrIndexes(t *testing.T) {
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
pk := tests.GetMakerTestKey(t)
|
||||
trustedForwarder := deployForwarder(t, ec, pk)
|
||||
@@ -86,65 +86,68 @@ func TestForwarderAddressIndexes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("forwarderAddressIndexes: %v", addressLocations)
|
||||
require.EqualValues(t, forwarderAddressIndices, addressLocations,
|
||||
"update forwarderAddressIndexes with above logged indexes to fix this test")
|
||||
t.Logf("forwarderAddrIndexes: %v", addressLocations)
|
||||
require.EqualValues(t, forwarderAddrIndices, addressLocations,
|
||||
"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.
|
||||
func TestCheckSwapFactoryContractCode(t *testing.T) {
|
||||
func TestCheckSwapCreatorContractCode(t *testing.T) {
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
pk := tests.GetMakerTestKey(t)
|
||||
trustedForwarderAddresses := []string{
|
||||
trustedForwarderAddrs := []string{
|
||||
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)
|
||||
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.Equal(t, addrHex, parsedTFAddr.Hex())
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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)
|
||||
_, err := CheckSwapFactoryContractCode(context.Background(), ec, contractAddr)
|
||||
require.ErrorIs(t, err, errInvalidSwapContract)
|
||||
_, err := CheckSwapCreatorContractCode(context.Background(), ec, contractAddr)
|
||||
require.ErrorIs(t, err, errInvalidSwapCreatorContract)
|
||||
}
|
||||
|
||||
func TestSepoliaContract(t *testing.T) {
|
||||
// comment out the next line to test the default sepolia contract
|
||||
t.Skip("requires access to non-vetted external sepolia node")
|
||||
const sepoliaEndpoint = "https://rpc.sepolia.org/"
|
||||
// TODO: CI's ETH_SEPOLIA_ENDPOINT is giving 404 errors
|
||||
endpoint := "" // os.Getenv("ETH_SEPOLIA_ENDPOINT")
|
||||
if endpoint == "" {
|
||||
endpoint = "https://rpc.sepolia.org/"
|
||||
}
|
||||
|
||||
// temporarily place a funded sepolia private key below to deploy the test contract
|
||||
const sepoliaKey = ""
|
||||
|
||||
ctx := context.Background()
|
||||
ec, err := ethclient.Dial(sepoliaEndpoint)
|
||||
ec, err := ethclient.Dial(endpoint)
|
||||
require.NoError(t, err)
|
||||
defer ec.Close()
|
||||
|
||||
parsedTFAddr, err := CheckSwapFactoryContractCode(ctx, ec, common.StagenetConfig().SwapFactoryAddress)
|
||||
if errors.Is(err, errInvalidSwapContract) && sepoliaKey != "" {
|
||||
parsedTFAddr, err := CheckSwapCreatorContractCode(ctx, ec, common.StagenetConfig().SwapCreatorAddr)
|
||||
if errors.Is(err, errInvalidSwapCreatorContract) && sepoliaKey != "" {
|
||||
pk, err := ethcrypto.HexToECDSA(sepoliaKey) //nolint:govet // shadow declaration of err
|
||||
require.NoError(t, err)
|
||||
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)
|
||||
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())
|
||||
} else {
|
||||
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 {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
|
||||
// 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
|
||||
@@ -20,14 +20,14 @@ import (
|
||||
|
||||
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.
|
||||
func DeploySwapFactoryWithKey(
|
||||
func DeploySwapCreatorWithKey(
|
||||
ctx context.Context,
|
||||
ec *ethclient.Client,
|
||||
privKey *ecdsa.PrivateKey,
|
||||
forwarderAddr ethcommon.Address,
|
||||
) (ethcommon.Address, *SwapFactory, error) {
|
||||
) (ethcommon.Address, *SwapCreator, error) {
|
||||
|
||||
txOpts, err := newTXOpts(ctx, ec, privKey)
|
||||
if err != nil {
|
||||
@@ -36,13 +36,13 @@ func DeploySwapFactoryWithKey(
|
||||
|
||||
if (forwarderAddr != ethcommon.Address{}) {
|
||||
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 {
|
||||
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())
|
||||
@@ -50,7 +50,7 @@ func DeploySwapFactoryWithKey(
|
||||
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
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -15,7 +15,7 @@ import (
|
||||
"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)
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
@@ -30,7 +30,7 @@ func TestSwapFactory_NewSwap_ERC20(t *testing.T) {
|
||||
testNewSwap(t, erc20Addr)
|
||||
}
|
||||
|
||||
func TestSwapFactory_Claim_ERC20(t *testing.T) {
|
||||
func TestSwapCreator_Claim_ERC20(t *testing.T) {
|
||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
@@ -48,7 +48,7 @@ func TestSwapFactory_Claim_ERC20(t *testing.T) {
|
||||
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)
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
@@ -62,7 +62,7 @@ func TestSwapFactory_RefundBeforeT0_ERC20(t *testing.T) {
|
||||
testRefundBeforeT0(t, erc20Addr, 2)
|
||||
}
|
||||
|
||||
func TestSwapFactory_RefundAfterT1_ERC20(t *testing.T) {
|
||||
func TestSwapCreator_RefundAfterT1_ERC20(t *testing.T) {
|
||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
|
||||
@@ -138,7 +138,7 @@ func (c *ethClient) Balance(ctx context.Context) (*big.Int, error) {
|
||||
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
|
||||
// supplied value is returned.
|
||||
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.
|
||||
// This file is a generated binding and any manual changes will be lost.
|
||||
|
||||
@@ -29,6 +26,7 @@ var (
|
||||
_ = common.Big1
|
||||
_ = types.BloomLookup
|
||||
_ = event.NewSubscription
|
||||
_ = abi.ConvertType
|
||||
)
|
||||
|
||||
// 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.
|
||||
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 {
|
||||
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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -12,7 +12,7 @@ import (
|
||||
"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.
|
||||
type swap struct {
|
||||
Owner common.Address `json:"owner" validate:"required"`
|
||||
@@ -26,8 +26,8 @@ type swap struct {
|
||||
Nonce *big.Int `json:"nonce" validate:"required"`
|
||||
}
|
||||
|
||||
// MarshalJSON provides JSON marshalling for SwapFactorySwap
|
||||
func (sfs *SwapFactorySwap) MarshalJSON() ([]byte, error) {
|
||||
// MarshalJSON provides JSON marshalling for SwapCreatorSwap
|
||||
func (sfs *SwapCreatorSwap) MarshalJSON() ([]byte, error) {
|
||||
return vjson.MarshalStruct(&swap{
|
||||
Owner: sfs.Owner,
|
||||
Claimer: sfs.Claimer,
|
||||
@@ -41,13 +41,13 @@ func (sfs *SwapFactorySwap) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalJSON provides JSON unmarshalling for SwapFactorySwap
|
||||
func (sfs *SwapFactorySwap) UnmarshalJSON(data []byte) error {
|
||||
// UnmarshalJSON provides JSON unmarshalling for SwapCreatorSwap
|
||||
func (sfs *SwapCreatorSwap) UnmarshalJSON(data []byte) error {
|
||||
s := &swap{}
|
||||
if err := vjson.UnmarshalStruct(data, s); err != nil {
|
||||
return err
|
||||
}
|
||||
*sfs = SwapFactorySwap{
|
||||
*sfs = SwapCreatorSwap{
|
||||
Owner: s.Owner,
|
||||
Claimer: s.Claimer,
|
||||
PubKeyClaim: s.PubKeyClaim,
|
||||
@@ -17,8 +17,8 @@ import (
|
||||
"github.com/athanorlabs/atomic-swap/common/vjson"
|
||||
)
|
||||
|
||||
func TestSwapFactorySwap_JSON(t *testing.T) {
|
||||
sf := &SwapFactorySwap{
|
||||
func TestSwapCreatorSwap_JSON(t *testing.T) {
|
||||
sf := &SwapCreatorSwap{
|
||||
Owner: ethcommon.HexToAddress("0xda9dfa130df4de4673b89022ee50ff26f6ea73cf"),
|
||||
Claimer: ethcommon.HexToAddress("0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"),
|
||||
PubKeyClaim: ethcommon.HexToHash("0x5ab9467e70d4e98567991f0179d1f82a3096ed7973f7aff9ea50f649cafa88b9"),
|
||||
@@ -44,7 +44,7 @@ func TestSwapFactorySwap_JSON(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, expectedJSON, string(jsonData))
|
||||
|
||||
sf2 := &SwapFactorySwap{}
|
||||
sf2 := &SwapCreatorSwap{}
|
||||
err = json.Unmarshal(jsonData, sf2)
|
||||
require.NoError(t, err)
|
||||
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
|
||||
// generated type.
|
||||
func TestSwapFactorySwap_JSON_fieldCountEqual(t *testing.T) {
|
||||
func TestSwapCreatorSwap_JSON_fieldCountEqual(t *testing.T) {
|
||||
numSwapFields := reflect.TypeOf(swap{}).NumField()
|
||||
numSwapFactorySwapFields := reflect.TypeOf(SwapFactorySwap{}).NumField()
|
||||
require.Equal(t, numSwapFactorySwapFields, numSwapFields)
|
||||
numSwapCreatorSwapFields := reflect.TypeOf(SwapCreatorSwap{}).NumField()
|
||||
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) {
|
||||
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.NotEqual(t, ethcommon.Address{}, address)
|
||||
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())
|
||||
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
|
||||
claimer := common.EthereumPrivateKeyToAddress(tests.GetMakerTestKey(t))
|
||||
@@ -106,7 +106,7 @@ func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// validate that off-chain swapID calculation matches the on-chain value
|
||||
swap := SwapFactorySwap{
|
||||
swap := SwapCreatorSwap{
|
||||
Owner: owner,
|
||||
Claimer: claimer,
|
||||
PubKeyClaim: pubKeyClaim,
|
||||
@@ -122,11 +122,11 @@ func testNewSwap(t *testing.T, asset ethcommon.Address) {
|
||||
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)
|
||||
}
|
||||
|
||||
func TestSwapFactory_Claim_vec(t *testing.T) {
|
||||
func TestSwapCreator_Claim_vec(t *testing.T) {
|
||||
secret, err := hex.DecodeString("D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759")
|
||||
require.NoError(t, err)
|
||||
pubX, err := hex.DecodeString("3AF1E1EFA4D1E1AD5CB9E3967E98E901DAFCD37C44CF0BFB6C216997F5EE51DF")
|
||||
@@ -147,11 +147,11 @@ func TestSwapFactory_Claim_vec(t *testing.T) {
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
|
||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
||||
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||
require.NoError(t, err)
|
||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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)
|
||||
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])
|
||||
require.NoError(t, err)
|
||||
|
||||
swap := SwapFactorySwap{
|
||||
swap := SwapCreatorSwap{
|
||||
Owner: addr,
|
||||
Claimer: addr,
|
||||
PubKeyClaim: cmt,
|
||||
@@ -211,19 +211,24 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
||||
cmt := res.Secp256k1PublicKey().Keccak256()
|
||||
|
||||
// deploy swap contract with claim key hash
|
||||
auth, conn, pkA := setupXMRTakerAuth(t)
|
||||
authOrig, conn, pkA := setupXMRTakerAuth(t)
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
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)
|
||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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 {
|
||||
require.NotNil(t, erc20Contract)
|
||||
tx, err = erc20Contract.Approve(auth, swapFactoryAddress, value)
|
||||
txOpts = *authOrig
|
||||
tx, err = erc20Contract.Approve(&txOpts, swapCreatorAddr, value)
|
||||
require.NoError(t, err)
|
||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
require.NoError(t, err)
|
||||
@@ -231,17 +236,17 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
||||
}
|
||||
|
||||
nonce := big.NewInt(0)
|
||||
txOpts = *authOrig
|
||||
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)
|
||||
require.NoError(t, err)
|
||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
require.NoError(t, err)
|
||||
t.Logf("gas cost to call new_swap: %d", receipt.GasUsed)
|
||||
auth.Value = big.NewInt(0)
|
||||
|
||||
require.Equal(t, newLogIndex+1, len(receipt.Logs))
|
||||
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])
|
||||
require.NoError(t, err)
|
||||
|
||||
swap := SwapFactorySwap{
|
||||
swap := SwapCreatorSwap{
|
||||
Owner: addr,
|
||||
Claimer: addr,
|
||||
PubKeyClaim: cmt,
|
||||
@@ -263,7 +268,8 @@ func testClaim(t *testing.T, asset ethcommon.Address, newLogIndex int, value *bi
|
||||
}
|
||||
|
||||
// set contract to Ready
|
||||
tx, err = contract.SetReady(auth, swap)
|
||||
txOpts = *authOrig
|
||||
tx, err = contract.SetReady(&txOpts, swap)
|
||||
require.NoError(t, err)
|
||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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
|
||||
secret := proof.Secret()
|
||||
copy(s[:], secret[:])
|
||||
tx, err = contract.Claim(auth, swap, s)
|
||||
txOpts = *authOrig
|
||||
tx, err = contract.Claim(&txOpts, swap, s)
|
||||
require.NoError(t, err)
|
||||
receipt, err = block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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)
|
||||
}
|
||||
|
||||
func TestSwapFactory_Claim_random(t *testing.T) {
|
||||
func TestSwapCreator_Claim_random(t *testing.T) {
|
||||
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)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
|
||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
||||
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||
require.NoError(t, err)
|
||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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)
|
||||
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])
|
||||
require.NoError(t, err)
|
||||
|
||||
swap := SwapFactorySwap{
|
||||
swap := SwapCreatorSwap{
|
||||
Owner: addr,
|
||||
Claimer: addr,
|
||||
PubKeyClaim: [32]byte{},
|
||||
@@ -352,7 +359,7 @@ func testRefundBeforeT0(t *testing.T, asset ethcommon.Address, newLogIndex int)
|
||||
require.Equal(t, StageCompleted, stage)
|
||||
}
|
||||
|
||||
func TestSwapFactory_Refund_beforeT0(t *testing.T) {
|
||||
func TestSwapCreator_Refund_beforeT0(t *testing.T) {
|
||||
testRefundBeforeT0(t, ethAssetAddress, 0)
|
||||
}
|
||||
|
||||
@@ -372,11 +379,11 @@ func testRefundAfterT1(t *testing.T, asset ethcommon.Address, newLogIndex int) {
|
||||
pub := pkA.Public().(*ecdsa.PublicKey)
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
|
||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
||||
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||
require.NoError(t, err)
|
||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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)
|
||||
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)))
|
||||
|
||||
swap := SwapFactorySwap{
|
||||
swap := SwapCreatorSwap{
|
||||
Owner: addr,
|
||||
Claimer: addr,
|
||||
PubKeyClaim: [32]byte{},
|
||||
@@ -428,11 +435,11 @@ func testRefundAfterT1(t *testing.T, asset ethcommon.Address, newLogIndex int) {
|
||||
require.Equal(t, StageCompleted, stage)
|
||||
}
|
||||
|
||||
func TestSwapFactory_Refund_afterT1(t *testing.T) {
|
||||
func TestSwapCreator_Refund_afterT1(t *testing.T) {
|
||||
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
|
||||
conn, chainID := tests.NewEthClient(t)
|
||||
|
||||
@@ -440,11 +447,11 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
||||
auth, err := bind.NewKeyedTransactorWithChainID(pkContractCreator, chainID)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, tx, contract, err := DeploySwapFactory(auth, conn, ethcommon.Address{})
|
||||
_, tx, contract, err := DeploySwapCreator(auth, conn, ethcommon.Address{})
|
||||
require.NoError(t, err)
|
||||
receipt, err := block.WaitForReceipt(context.Background(), conn, tx.Hash())
|
||||
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
|
||||
type swapCase struct {
|
||||
@@ -452,7 +459,7 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
||||
walletKey *ecdsa.PrivateKey
|
||||
id [32]byte
|
||||
secret [32]byte
|
||||
swap SwapFactorySwap
|
||||
swap SwapCreatorSwap
|
||||
}
|
||||
|
||||
getAuth := func(sc *swapCase) *bind.TransactOpts {
|
||||
@@ -481,7 +488,7 @@ func TestSwapFactory_MultipleSwaps(t *testing.T) {
|
||||
sc.walletKey = tests.GetTestKeyByIndex(t, i)
|
||||
addrSwap := crypto.PubkeyToAddress(*sc.walletKey.Public().(*ecdsa.PublicKey))
|
||||
|
||||
sc.swap = SwapFactorySwap{
|
||||
sc.swap = SwapCreatorSwap{
|
||||
Owner: addrSwap,
|
||||
Claimer: addrSwap,
|
||||
PubKeyClaim: res.Secp256k1PublicKey().Keccak256(),
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
// Swap stage values that match the names and indexes of the Stage enum in
|
||||
// the SwapFactory contract
|
||||
// the SwapCreator contract
|
||||
const (
|
||||
StageInvalid byte = iota
|
||||
StagePending
|
||||
@@ -30,10 +30,10 @@ const (
|
||||
)
|
||||
|
||||
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
|
||||
// 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)
|
||||
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
|
||||
// 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)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to create uint256 type: %s", err))
|
||||
@@ -116,7 +116,7 @@ func (sfs *SwapFactorySwap) SwapID() types.Hash {
|
||||
)
|
||||
if err != nil {
|
||||
// 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.
|
||||
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")
|
||||
}
|
||||
|
||||
// abiSF, err := abi.JSON(strings.NewReader(SwapFactoryMetaData.ABI))
|
||||
// abiSF, err := abi.JSON(strings.NewReader(SwapCreatorMetaData.ABI))
|
||||
// if err != nil {
|
||||
// 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")
|
||||
}
|
||||
|
||||
// abi, err := abi.JSON(strings.NewReader(SwapFactoryMetaData.ABI))
|
||||
// abi, err := abi.JSON(strings.NewReader(SwapCreatorMetaData.ABI))
|
||||
// if err != nil {
|
||||
// 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.
|
||||
func GetIDFromLog(log *ethtypes.Log) ([32]byte, error) {
|
||||
abi := SwapFactoryParsedABI
|
||||
abi := SwapCreatorParsedABI
|
||||
|
||||
const event = "New"
|
||||
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.
|
||||
func GetTimeoutsFromLog(log *ethtypes.Log) (*big.Int, *big.Int, error) {
|
||||
abi := SwapFactoryParsedABI
|
||||
abi := SwapCreatorParsedABI
|
||||
|
||||
const event = "New"
|
||||
if log.Topics[0] != abi.Events[event].ID {
|
||||
|
||||
@@ -6,6 +6,7 @@ package watcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math/big"
|
||||
"time"
|
||||
|
||||
@@ -13,14 +14,18 @@ import (
|
||||
ethcommon "github.com/ethereum/go-ethereum/common"
|
||||
ethtypes "github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/ethclient"
|
||||
ethrpc "github.com/ethereum/go-ethereum/rpc"
|
||||
logging "github.com/ipfs/go-log"
|
||||
)
|
||||
|
||||
var (
|
||||
log = logging.Logger("ethereum/watcher")
|
||||
const (
|
||||
checkForBlocksTimeout = time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
log = logging.Logger("ethereum/watcher")
|
||||
)
|
||||
|
||||
// EventFilter filters the chain for specific events (logs).
|
||||
// When it finds a desired log, it puts it into its outbound channel.
|
||||
type EventFilter struct {
|
||||
@@ -70,6 +75,9 @@ func (f *EventFilter) Start() error {
|
||||
currHeader, err := f.ec.HeaderByNumber(f.ctx, nil)
|
||||
if err != nil {
|
||||
log.Errorf("failed to get header in event watcher: %s", err)
|
||||
if errors.Is(err, ethrpc.ErrClientQuit) {
|
||||
return // non-recoverable error
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -85,7 +93,9 @@ func (f *EventFilter) Start() error {
|
||||
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 {
|
||||
if l.Topics[0] != f.topic {
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
const (
|
||||
// ProtocolID is the base atomic swap network protocol ID prefix. The full ID
|
||||
// includes the chain ID at the end.
|
||||
ProtocolID = "/atomic-swap/0.2"
|
||||
ProtocolID = "/atomic-swap/0.3"
|
||||
maxMessageSize = 1 << 17
|
||||
maxRelayMessageSize = 2048
|
||||
)
|
||||
|
||||
@@ -79,8 +79,14 @@ func (s *mockSwapState) Exit() error {
|
||||
func basicTestConfig(t *testing.T) *Config {
|
||||
// t.TempDir() is unique on every call. Don't reuse this config with multiple hosts.
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
})
|
||||
|
||||
return &Config{
|
||||
Ctx: context.Background(),
|
||||
Ctx: ctx,
|
||||
DataDir: tmpDir,
|
||||
Port: 0, // OS randomized libp2p port
|
||||
KeyFile: path.Join(tmpDir, "node.key"),
|
||||
|
||||
@@ -158,7 +158,7 @@ type NotifyETHLocked struct {
|
||||
Address ethcommon.Address `json:"address" validate:"required"`
|
||||
TxHash types.Hash `json:"txHash" validate:"required"`
|
||||
ContractSwapID types.Hash `json:"contractSwapID" validate:"required"`
|
||||
ContractSwap *contracts.SwapFactorySwap `json:"contractSwap" validate:"required"`
|
||||
ContractSwap *contracts.SwapCreatorSwap `json:"contractSwap" validate:"required"`
|
||||
}
|
||||
|
||||
// String ...
|
||||
|
||||
@@ -18,11 +18,11 @@ type RelayClaimRequest struct {
|
||||
// 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,
|
||||
// because it advertised in the DHT.
|
||||
OfferID *types.Hash `json:"offerID"`
|
||||
SwapFactoryAddress ethcommon.Address `json:"swapFactoryAddress" validate:"required"`
|
||||
Swap *contracts.SwapFactorySwap `json:"swap" validate:"required"`
|
||||
Secret []byte `json:"secret" validate:"required,len=32"`
|
||||
Signature []byte `json:"signature" validate:"required,len=65"`
|
||||
OfferID *types.Hash `json:"offerID"`
|
||||
SwapCreatorAddr ethcommon.Address `json:"swapCreatorAddr" validate:"required"`
|
||||
Swap *contracts.SwapCreatorSwap `json:"swap" validate:"required"`
|
||||
Secret []byte `json:"secret" validate:"required,len=32"`
|
||||
Signature []byte `json:"signature" validate:"required,len=65"`
|
||||
}
|
||||
|
||||
// RelayClaimResponse implements common.Message for our p2p relay claim responses
|
||||
|
||||
@@ -60,8 +60,8 @@ func createTestClaimRequest() *message.RelayClaimRequest {
|
||||
sig := [65]byte{0x1}
|
||||
|
||||
req := &message.RelayClaimRequest{
|
||||
SwapFactoryAddress: ethcommon.Address{0x1},
|
||||
Swap: &contracts.SwapFactorySwap{
|
||||
SwapCreatorAddr: ethcommon.Address{0x1},
|
||||
Swap: &contracts.SwapCreatorSwap{
|
||||
Owner: ethcommon.Address{0x1},
|
||||
Claimer: ethcommon.Address{0x1},
|
||||
PubKeyClaim: [32]byte{0x1},
|
||||
|
||||
@@ -64,15 +64,15 @@ type Backend interface {
|
||||
NewTxSender(asset ethcommon.Address, erc20Contract *contracts.IERC20) (txsender.Sender, error)
|
||||
|
||||
// helpers
|
||||
NewSwapFactory(addr ethcommon.Address) (*contracts.SwapFactory, error)
|
||||
NewSwapCreator(addr ethcommon.Address) (*contracts.SwapCreator, error)
|
||||
HandleRelayClaimRequest(request *message.RelayClaimRequest) (*message.RelayClaimResponse, error)
|
||||
|
||||
// getters
|
||||
Ctx() context.Context
|
||||
Env() common.Environment
|
||||
SwapManager() swap.Manager
|
||||
Contract() *contracts.SwapFactory
|
||||
ContractAddr() ethcommon.Address
|
||||
SwapCreator() *contracts.SwapCreator
|
||||
SwapCreatorAddr() ethcommon.Address
|
||||
SwapTimeout() time.Duration
|
||||
XMRDepositAddress(offerID *types.Hash) *mcrypto.Address
|
||||
|
||||
@@ -101,9 +101,9 @@ type backend struct {
|
||||
perSwapXMRDepositAddr map[types.Hash]*mcrypto.Address
|
||||
|
||||
// swap contract
|
||||
contract *contracts.SwapFactory
|
||||
contractAddr ethcommon.Address
|
||||
swapTimeout time.Duration
|
||||
swapCreator *contracts.SwapCreator
|
||||
swapCreatorAddr ethcommon.Address
|
||||
swapTimeout time.Duration
|
||||
|
||||
// network interface
|
||||
NetSender
|
||||
@@ -111,23 +111,23 @@ type backend struct {
|
||||
|
||||
// Config is the config for the Backend
|
||||
type Config struct {
|
||||
Ctx context.Context
|
||||
MoneroClient monero.WalletClient
|
||||
EthereumClient extethclient.EthClient
|
||||
Environment common.Environment
|
||||
SwapFactoryAddress ethcommon.Address
|
||||
SwapManager swap.Manager
|
||||
RecoveryDB RecoveryDB
|
||||
Net NetSender
|
||||
Ctx context.Context
|
||||
MoneroClient monero.WalletClient
|
||||
EthereumClient extethclient.EthClient
|
||||
Environment common.Environment
|
||||
SwapCreatorAddr ethcommon.Address
|
||||
SwapManager swap.Manager
|
||||
RecoveryDB RecoveryDB
|
||||
Net NetSender
|
||||
}
|
||||
|
||||
// NewBackend returns a new Backend
|
||||
func NewBackend(cfg *Config) (Backend, error) {
|
||||
if (cfg.SwapFactoryAddress == ethcommon.Address{}) {
|
||||
if (cfg.SwapCreatorAddr == ethcommon.Address{}) {
|
||||
return nil, errNilSwapContractOrAddress
|
||||
}
|
||||
|
||||
swapFactory, err := contracts.NewSwapFactory(cfg.SwapFactoryAddress, cfg.EthereumClient.Raw())
|
||||
swapCreator, err := contracts.NewSwapCreator(cfg.SwapCreatorAddr, cfg.EthereumClient.Raw())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -137,8 +137,8 @@ func NewBackend(cfg *Config) (Backend, error) {
|
||||
env: cfg.Environment,
|
||||
moneroWallet: cfg.MoneroClient,
|
||||
ethClient: cfg.EthereumClient,
|
||||
contract: swapFactory,
|
||||
contractAddr: cfg.SwapFactoryAddress,
|
||||
swapCreator: swapCreator,
|
||||
swapCreatorAddr: cfg.SwapCreatorAddr,
|
||||
swapManager: cfg.SwapManager,
|
||||
swapTimeout: common.SwapTimeoutFromEnv(cfg.Environment),
|
||||
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) {
|
||||
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 {
|
||||
return b.recoveryDB
|
||||
}
|
||||
|
||||
func (b *backend) Contract() *contracts.SwapFactory {
|
||||
return b.contract
|
||||
func (b *backend) SwapCreator() *contracts.SwapCreator {
|
||||
return b.swapCreator
|
||||
}
|
||||
|
||||
func (b *backend) ContractAddr() ethcommon.Address {
|
||||
return b.contractAddr
|
||||
func (b *backend) SwapCreatorAddr() ethcommon.Address {
|
||||
return b.swapCreatorAddr
|
||||
}
|
||||
|
||||
func (b *backend) Ctx() context.Context {
|
||||
@@ -197,8 +197,8 @@ func (b *backend) SetSwapTimeout(timeout time.Duration) {
|
||||
b.swapTimeout = timeout
|
||||
}
|
||||
|
||||
func (b *backend) NewSwapFactory(addr ethcommon.Address) (*contracts.SwapFactory, error) {
|
||||
return contracts.NewSwapFactory(addr, b.ethClient.Raw())
|
||||
func (b *backend) NewSwapCreator(addr ethcommon.Address) (*contracts.SwapCreator, error) {
|
||||
return contracts.NewSwapCreator(addr, b.ethClient.Raw())
|
||||
}
|
||||
|
||||
// XMRDepositAddress returns the per-swap override deposit address, if a
|
||||
@@ -258,6 +258,6 @@ func (b *backend) HandleRelayClaimRequest(request *message.RelayClaimRequest) (*
|
||||
b.Ctx(),
|
||||
request,
|
||||
b.ETHClient(),
|
||||
b.ContractAddr(),
|
||||
b.SwapCreatorAddr(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
|
||||
var (
|
||||
// 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")
|
||||
)
|
||||
|
||||
@@ -42,7 +42,7 @@ func Test_InfoMarshal(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
expectedJSON := `{
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"peerID": "12D3KooWQQRJuKTZ35eiHGNPGDpQqjpJSdaxEMJRxi6NWFrrvQVi",
|
||||
"offerID": "0x0102030405060708091011121314151617181920212223242526272829303132",
|
||||
"provides": "XMR",
|
||||
|
||||
@@ -68,7 +68,7 @@ func NewExternalSender(
|
||||
return &ExternalSender{
|
||||
ctx: ctx,
|
||||
ec: ec,
|
||||
abi: contracts.SwapFactoryParsedABI,
|
||||
abi: contracts.SwapCreatorParsedABI,
|
||||
contractAddr: contractAddr,
|
||||
erc20Addr: erc20Addr,
|
||||
out: make(chan *Transaction),
|
||||
@@ -77,7 +77,7 @@ func NewExternalSender(
|
||||
}
|
||||
|
||||
// SetContract ...
|
||||
func (s *ExternalSender) SetContract(_ *contracts.SwapFactory) {}
|
||||
func (s *ExternalSender) SetContract(_ *contracts.SwapCreator) {}
|
||||
|
||||
// SetContractAddress ...
|
||||
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
|
||||
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)
|
||||
if err != nil {
|
||||
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
|
||||
func (s *ExternalSender) Claim(
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret [32]byte,
|
||||
) (*ethtypes.Receipt, error) {
|
||||
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
|
||||
func (s *ExternalSender) Refund(
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret [32]byte,
|
||||
) (*ethtypes.Receipt, error) {
|
||||
input, err := s.abi.Pack("refund", swap, secret)
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
|
||||
// Sender signs and submits transactions to the chain
|
||||
type Sender interface {
|
||||
SetContract(*contracts.SwapFactory)
|
||||
SetContract(*contracts.SwapCreator)
|
||||
SetContractAddress(ethcommon.Address)
|
||||
Approve(spender ethcommon.Address, amount *big.Int) (*ethtypes.Receipt, error) // for ERC20 swaps
|
||||
NewSwap(
|
||||
@@ -36,15 +36,15 @@ type Sender interface {
|
||||
ethAsset types.EthAsset,
|
||||
amount *big.Int,
|
||||
) (*ethtypes.Receipt, error)
|
||||
SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.Receipt, error)
|
||||
Claim(swap *contracts.SwapFactorySwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||
Refund(swap *contracts.SwapFactorySwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||
SetReady(swap *contracts.SwapCreatorSwap) (*ethtypes.Receipt, error)
|
||||
Claim(swap *contracts.SwapCreatorSwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||
Refund(swap *contracts.SwapCreatorSwap, secret [32]byte) (*ethtypes.Receipt, error)
|
||||
}
|
||||
|
||||
type privateKeySender struct {
|
||||
ctx context.Context
|
||||
ethClient extethclient.EthClient
|
||||
swapContract *contracts.SwapFactory
|
||||
swapContract *contracts.SwapCreator
|
||||
erc20Contract *contracts.IERC20
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ type privateKeySender struct {
|
||||
func NewSenderWithPrivateKey(
|
||||
ctx context.Context,
|
||||
ethClient extethclient.EthClient,
|
||||
swapContract *contracts.SwapFactory,
|
||||
swapContract *contracts.SwapCreator,
|
||||
erc20Contract *contracts.IERC20,
|
||||
) Sender {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ func (s *privateKeySender) NewSwap(
|
||||
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()
|
||||
defer s.ethClient.Unlock()
|
||||
txOpts, err := s.ethClient.TxOpts(s.ctx)
|
||||
@@ -156,7 +156,7 @@ func (s *privateKeySender) SetReady(swap *contracts.SwapFactorySwap) (*ethtypes.
|
||||
}
|
||||
|
||||
func (s *privateKeySender) Claim(
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret [32]byte,
|
||||
) (*ethtypes.Receipt, error) {
|
||||
s.ethClient.Lock()
|
||||
@@ -182,7 +182,7 @@ func (s *privateKeySender) Claim(
|
||||
}
|
||||
|
||||
func (s *privateKeySender) Refund(
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret [32]byte,
|
||||
) (*ethtypes.Receipt, error) {
|
||||
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)
|
||||
}
|
||||
|
||||
if tx.To() == nil || *(tx.To()) != s.contractAddr {
|
||||
if tx.To() == nil || *(tx.To()) != s.swapCreatorAddr {
|
||||
return errInvalidETHLockedTransaction
|
||||
}
|
||||
|
||||
@@ -45,9 +45,9 @@ func (s *swapState) checkContract(txHash ethcommon.Hash) error {
|
||||
return errCannotFindNewLog
|
||||
}
|
||||
|
||||
var event *contracts.SwapFactoryNew
|
||||
var event *contracts.SwapCreatorNew
|
||||
for _, log := range receipt.Logs {
|
||||
event, err = s.Contract().ParseNew(*log)
|
||||
event, err = s.SwapCreator().ParseNew(*log)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func (s *swapState) relayClaimWithXMRTaker(request *message.RelayClaimRequest) (
|
||||
s.ctx,
|
||||
s.ETHClient().Raw(),
|
||||
response.TxHash,
|
||||
s.contractAddr,
|
||||
s.swapCreatorAddr,
|
||||
s.contractSwapID,
|
||||
s.getSecret(),
|
||||
)
|
||||
@@ -159,7 +159,7 @@ func (s *swapState) claimWithAdvertisedRelayers(request *message.RelayClaimReque
|
||||
s.ctx,
|
||||
s.ETHClient().Raw(),
|
||||
resp.TxHash,
|
||||
s.contractAddr,
|
||||
s.swapCreatorAddr,
|
||||
s.contractSwapID,
|
||||
s.getSecret(),
|
||||
)
|
||||
@@ -183,7 +183,7 @@ func (s *swapState) claimWithAdvertisedRelayers(request *message.RelayClaimReque
|
||||
// operations more generally. Note that the receipt returned is for a
|
||||
// transaction created by the remote relayer, not by us.
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -194,8 +194,8 @@ func (s *swapState) claimWithRelay() (*ethtypes.Receipt, error) {
|
||||
s.ctx,
|
||||
s.ETHClient().PrivateKey(),
|
||||
s.ETHClient().Raw(),
|
||||
s.contractAddr,
|
||||
forwarderAddress,
|
||||
s.swapCreatorAddr,
|
||||
forwarderAddr,
|
||||
s.contractSwap,
|
||||
&secret,
|
||||
)
|
||||
|
||||
@@ -84,7 +84,7 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
||||
addr := crypto.PubkeyToAddress(*pub)
|
||||
|
||||
// deploy forwarder
|
||||
forwarderAddress, tx, forwarderContract, err := gsnforwarder.DeployForwarder(txOpts, ec.Raw())
|
||||
forwarderAddr, tx, forwarderContract, err := gsnforwarder.DeployForwarder(txOpts, ec.Raw())
|
||||
require.NoError(t, err)
|
||||
receipt, err := block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
||||
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)
|
||||
|
||||
// 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)
|
||||
receipt, err = block.WaitForReceipt(ctx, ec.Raw(), tx.Hash())
|
||||
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 {
|
||||
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])
|
||||
require.NoError(t, err)
|
||||
|
||||
swap := &contracts.SwapFactorySwap{
|
||||
swap := &contracts.SwapCreatorSwap{
|
||||
Owner: addr,
|
||||
Claimer: addr,
|
||||
PubKeyClaim: cmt,
|
||||
@@ -168,7 +168,7 @@ func testSwapStateClaimRelayer(t *testing.T, sk *ecdsa.PrivateKey, asset types.E
|
||||
sk,
|
||||
ec.Raw(),
|
||||
contractAddr,
|
||||
forwarderAddress,
|
||||
forwarderAddr,
|
||||
swap,
|
||||
&secret,
|
||||
)
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestSwapState_handleEvent_EventContractReady(t *testing.T) {
|
||||
|
||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||
require.NoError(t, err)
|
||||
tx, err := s.Contract().SetReady(txOpts, *s.contractSwap)
|
||||
tx, err := s.SwapCreator().SetReady(txOpts, *s.contractSwap)
|
||||
require.NoError(t, err)
|
||||
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)
|
||||
require.NoError(t, err)
|
||||
|
||||
var forwarderAddress ethcommon.Address
|
||||
_, tx, _, err := contracts.DeploySwapFactory(txOpts, ec, forwarderAddress)
|
||||
var forwarderAddr ethcommon.Address
|
||||
_, tx, _, err := contracts.DeploySwapCreator(txOpts, ec, forwarderAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -115,14 +115,14 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
||||
|
||||
net := new(mockNet)
|
||||
bcfg := &backend.Config{
|
||||
Ctx: ctx,
|
||||
MoneroClient: monero.CreateWalletClient(t),
|
||||
EthereumClient: extendedEC,
|
||||
Environment: common.Development,
|
||||
SwapFactoryAddress: addr,
|
||||
SwapManager: newSwapManager(t),
|
||||
Net: net,
|
||||
RecoveryDB: rdb,
|
||||
Ctx: ctx,
|
||||
MoneroClient: monero.CreateWalletClient(t),
|
||||
EthereumClient: extendedEC,
|
||||
Environment: common.Development,
|
||||
SwapCreatorAddr: addr,
|
||||
SwapManager: newSwapManager(t),
|
||||
Net: net,
|
||||
RecoveryDB: rdb,
|
||||
}
|
||||
|
||||
b, err := backend.NewBackend(bcfg)
|
||||
@@ -168,7 +168,7 @@ func TestInstance_createOngoingSwap(t *testing.T) {
|
||||
rdb := inst.backend.RecoveryDB().(*backend.MockRecoveryDB)
|
||||
|
||||
ec := inst.backend.ETHClient()
|
||||
contract := inst.backend.Contract()
|
||||
contract := inst.backend.SwapCreator()
|
||||
contractSwap, contractSwapID, _ := newTestSwap(
|
||||
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().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
||||
StartNumber: big.NewInt(1),
|
||||
ContractAddress: inst.backend.ContractAddr(),
|
||||
SwapCreatorAddr: inst.backend.SwapCreatorAddr(),
|
||||
SwapID: contractSwapID,
|
||||
Swap: &contracts.SwapFactorySwap{
|
||||
Swap: &contracts.SwapCreatorSwap{
|
||||
Timeout0: big.NewInt(1),
|
||||
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,
|
||||
// in which case it's not relevant to us and we don't need to verify it.
|
||||
// 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 {
|
||||
return err
|
||||
}
|
||||
@@ -130,7 +130,7 @@ func (s *swapState) handleNotifyETHLocked(msg *message.NotifyETHLocked) error {
|
||||
StartNumber: receipt.BlockNumber,
|
||||
SwapID: s.contractSwapID,
|
||||
Swap: s.contractSwap,
|
||||
ContractAddress: contractAddr,
|
||||
SwapCreatorAddr: contractAddr,
|
||||
}
|
||||
|
||||
if err = s.Backend.RecoveryDB().PutContractSwapInfo(s.OfferID(), ethInfo); err != nil {
|
||||
|
||||
@@ -63,11 +63,11 @@ type swapState struct {
|
||||
pubkeys *mcrypto.PublicKeyPair
|
||||
|
||||
// swap contract and timeouts in it
|
||||
contract *contracts.SwapFactory
|
||||
contractAddr ethcommon.Address
|
||||
contractSwapID [32]byte
|
||||
contractSwap *contracts.SwapFactorySwap
|
||||
t0, t1 time.Time
|
||||
contract *contracts.SwapCreator
|
||||
swapCreatorAddr ethcommon.Address
|
||||
contractSwapID [32]byte
|
||||
contractSwap *contracts.SwapCreatorSwap
|
||||
t0, t1 time.Time
|
||||
|
||||
// XMRTaker's keys for this session
|
||||
xmrtakerPublicSpendKey *mcrypto.PublicKey
|
||||
@@ -182,7 +182,7 @@ func checkIfAlreadyClaimed(
|
||||
) (bool, error) {
|
||||
// check if swap actually completed and we didn't realize for some reason
|
||||
// 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 {
|
||||
return false, err
|
||||
}
|
||||
@@ -206,7 +206,7 @@ func checkIfAlreadyClaimed(
|
||||
|
||||
filterQuery := ethereum.FilterQuery{
|
||||
FromBlock: ethSwapInfo.StartNumber,
|
||||
Addresses: []ethcommon.Address{ethSwapInfo.ContractAddress},
|
||||
Addresses: []ethcommon.Address{ethSwapInfo.SwapCreatorAddr},
|
||||
}
|
||||
|
||||
claimedTopic := common.GetTopic(common.ClaimedEventSignature)
|
||||
@@ -309,7 +309,7 @@ func newSwapStateFromOngoing(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = s.setContract(ethSwapInfo.ContractAddress)
|
||||
err = s.setContract(ethSwapInfo.SwapCreatorAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -361,7 +361,7 @@ func newSwapState(
|
||||
readyWatcher := watcher.NewEventFilter(
|
||||
ctx,
|
||||
b.ETHClient().Raw(),
|
||||
b.ContractAddr(),
|
||||
b.SwapCreatorAddr(),
|
||||
ethStartNumber,
|
||||
readyTopic,
|
||||
logReadyCh,
|
||||
@@ -370,7 +370,7 @@ func newSwapState(
|
||||
refundedWatcher := watcher.NewEventFilter(
|
||||
ctx,
|
||||
b.ETHClient().Raw(),
|
||||
b.ContractAddr(),
|
||||
b.SwapCreatorAddr(),
|
||||
ethStartNumber,
|
||||
refundedTopic,
|
||||
logRefundedCh,
|
||||
@@ -624,10 +624,10 @@ func (s *swapState) setXMRTakerKeys(
|
||||
|
||||
// setContract sets the contract in which XMRTaker has locked her ETH.
|
||||
func (s *swapState) setContract(address ethcommon.Address) error {
|
||||
s.contractAddr = address
|
||||
s.swapCreatorAddr = address
|
||||
|
||||
var err error
|
||||
s.contract, err = s.NewSwapFactory(address)
|
||||
s.contract, err = s.NewSwapCreator(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestSwapStateOngoing_ClaimFunds(t *testing.T) {
|
||||
|
||||
txOpts, err := swapState.ETHClient().TxOpts(swapState.Backend.Ctx())
|
||||
require.NoError(t, err)
|
||||
tx, err := swapState.Contract().SetReady(txOpts, *swapState.contractSwap)
|
||||
tx, err := swapState.SwapCreator().SetReady(txOpts, *swapState.contractSwap)
|
||||
require.NoError(t, err)
|
||||
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestSwapStateOngoing_ClaimFunds(t *testing.T) {
|
||||
StartNumber: big.NewInt(int64(startNum)),
|
||||
SwapID: swapState.contractSwapID,
|
||||
Swap: swapState.contractSwap,
|
||||
ContractAddress: swapState.Backend.ContractAddr(),
|
||||
SwapCreatorAddr: swapState.Backend.SwapCreatorAddr(),
|
||||
}
|
||||
|
||||
swapState.info.Status = types.XMRLocked
|
||||
@@ -101,7 +101,7 @@ func TestSwapStateOngoing_Refund(t *testing.T) {
|
||||
ctx := s.Backend.Ctx()
|
||||
txOpts, err := s.ETHClient().TxOpts(ctx)
|
||||
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)
|
||||
receipt, err := block.WaitForReceipt(ctx, s.ETHClient().Raw(), tx.Hash())
|
||||
require.NoError(t, err)
|
||||
@@ -111,7 +111,7 @@ func TestSwapStateOngoing_Refund(t *testing.T) {
|
||||
StartNumber: big.NewInt(int64(startNum)),
|
||||
SwapID: s.contractSwapID,
|
||||
Swap: s.contractSwap,
|
||||
ContractAddress: s.Backend.ContractAddr(),
|
||||
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||
}
|
||||
|
||||
s.info.Status = types.XMRLocked
|
||||
|
||||
@@ -75,11 +75,11 @@ func newTestXMRTakerSendKeysMessage(t *testing.T) (*message.SendKeysMessage, *pc
|
||||
func newTestSwap(
|
||||
t *testing.T,
|
||||
ec extethclient.EthClient,
|
||||
contract *contracts.SwapFactory,
|
||||
contract *contracts.SwapCreator,
|
||||
claimKey, refundKey types.Hash,
|
||||
amount *big.Int,
|
||||
timeout time.Duration,
|
||||
) (*contracts.SwapFactorySwap, [32]byte, ethcommon.Hash) {
|
||||
) (*contracts.SwapCreatorSwap, [32]byte, ethcommon.Hash) {
|
||||
tm := big.NewInt(int64(timeout.Seconds()))
|
||||
txOpts, err := ec.TxOpts(context.Background())
|
||||
require.NoError(t, err)
|
||||
@@ -100,7 +100,7 @@ func newTestSwap(
|
||||
t0, t1, err := contracts.GetTimeoutsFromLog(receipt.Logs[0])
|
||||
require.NoError(t, err)
|
||||
|
||||
contractSwap := &contracts.SwapFactorySwap{
|
||||
contractSwap := &contracts.SwapCreatorSwap{
|
||||
Owner: ethAddr,
|
||||
Claimer: ethAddr,
|
||||
PubKeyClaim: claimKey,
|
||||
@@ -128,7 +128,7 @@ func newSwap(
|
||||
}
|
||||
|
||||
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
|
||||
@@ -153,7 +153,7 @@ func TestSwapState_ClaimFunds(t *testing.T) {
|
||||
|
||||
txOpts, err := swapState.ETHClient().TxOpts(swapState.ctx)
|
||||
require.NoError(t, err)
|
||||
tx, err := swapState.Contract().SetReady(txOpts, *swapState.contractSwap)
|
||||
tx, err := swapState.SwapCreator().SetReady(txOpts, *swapState.contractSwap)
|
||||
require.NoError(t, err)
|
||||
tests.MineTransaction(t, swapState.ETHClient().Raw(), tx)
|
||||
|
||||
@@ -201,7 +201,7 @@ func TestSwapState_HandleProtocolMessage_NotifyETHLocked_ok(t *testing.T) {
|
||||
duration := common.SwapTimeoutFromEnv(common.Development)
|
||||
hash := newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
||||
desiredAmount.BigInt(), duration)
|
||||
addr := s.ContractAddr()
|
||||
addr := s.SwapCreatorAddr()
|
||||
|
||||
msg = &message.NotifyETHLocked{
|
||||
Address: addr,
|
||||
@@ -235,7 +235,7 @@ func TestSwapState_HandleProtocolMessage_NotifyETHLocked_timeout(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
_ = newSwap(t, s, s.secp256k1Pub.Keccak256(), s.xmrtakerSecp256K1PublicKey.Keccak256(),
|
||||
desiredAmount.BigInt(), duration)
|
||||
addr := s.ContractAddr()
|
||||
addr := s.SwapCreatorAddr()
|
||||
|
||||
err = s.setContract(addr)
|
||||
require.NoError(t, err)
|
||||
@@ -287,7 +287,7 @@ func TestSwapState_handleRefund(t *testing.T) {
|
||||
|
||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||
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)
|
||||
receipt, err := block.WaitForReceipt(s.Backend.Ctx(), s.ETHClient().Raw(), tx.Hash())
|
||||
require.NoError(t, err)
|
||||
@@ -342,7 +342,7 @@ func TestSwapState_Exit_Reclaim(t *testing.T) {
|
||||
|
||||
txOpts, err := s.ETHClient().TxOpts(s.ctx)
|
||||
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)
|
||||
receipt := tests.MineTransaction(t, s.ETHClient().Raw(), tx)
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ func (s *swapState) tryClaim() error {
|
||||
|
||||
func (s *swapState) filterForClaim() (*mcrypto.PrivateSpendKey, error) {
|
||||
logs, err := s.ETHClient().Raw().FilterLogs(s.ctx, eth.FilterQuery{
|
||||
Addresses: []ethcommon.Address{s.ContractAddr()},
|
||||
Addresses: []ethcommon.Address{s.SwapCreatorAddr()},
|
||||
Topics: [][]ethcommon.Hash{{claimedTopic}},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -44,7 +44,7 @@ func lockXMRAndCheckForReadyLog(t *testing.T, s *swapState, xmrAddr *mcrypto.Add
|
||||
readyWatcher := watcher.NewEventFilter(
|
||||
s.Backend.Ctx(),
|
||||
s.Backend.ETHClient().Raw(),
|
||||
s.Backend.ContractAddr(),
|
||||
s.Backend.SwapCreatorAddr(),
|
||||
ethHeader.Number,
|
||||
readyTopic,
|
||||
logReadyCh,
|
||||
|
||||
@@ -66,8 +66,8 @@ func TestInstance_createOngoingSwap(t *testing.T) {
|
||||
rdb.EXPECT().GetCounterpartySwapPrivateKey(s.OfferID).Return(nil, errors.New("some error"))
|
||||
rdb.EXPECT().GetContractSwapInfo(s.OfferID).Return(&db.EthereumSwapInfo{
|
||||
StartNumber: big.NewInt(1),
|
||||
ContractAddress: inst.backend.ContractAddr(),
|
||||
Swap: &contracts.SwapFactorySwap{
|
||||
SwapCreatorAddr: inst.backend.SwapCreatorAddr(),
|
||||
Swap: &contracts.SwapCreatorSwap{
|
||||
Timeout0: big.NewInt(1),
|
||||
Timeout1: big.NewInt(2),
|
||||
},
|
||||
|
||||
@@ -136,7 +136,7 @@ func (s *swapState) handleSendKeysMessage(msg *message.SendKeysMessage) (common.
|
||||
go s.checkForXMRLock()
|
||||
|
||||
out := &message.NotifyETHLocked{
|
||||
Address: s.ContractAddr(),
|
||||
Address: s.SwapCreatorAddr(),
|
||||
TxHash: receipt.TxHash,
|
||||
ContractSwapID: s.contractSwapID,
|
||||
ContractSwap: s.contractSwap,
|
||||
|
||||
@@ -73,7 +73,7 @@ type swapState struct {
|
||||
|
||||
// swap contract and timeouts in it; set once contract is deployed
|
||||
contractSwapID [32]byte
|
||||
contractSwap *contracts.SwapFactorySwap
|
||||
contractSwap *contracts.SwapCreatorSwap
|
||||
t0, t1 time.Time
|
||||
|
||||
// tracks the state of the swap
|
||||
@@ -182,8 +182,8 @@ func newSwapStateFromOngoing(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if b.ContractAddr() != ethSwapInfo.ContractAddress {
|
||||
return nil, errContractAddrMismatch(ethSwapInfo.ContractAddress.String())
|
||||
if b.SwapCreatorAddr() != ethSwapInfo.SwapCreatorAddr {
|
||||
return nil, errContractAddrMismatch(ethSwapInfo.SwapCreatorAddr.String())
|
||||
}
|
||||
|
||||
s.setTimeouts(ethSwapInfo.Swap.Timeout0, ethSwapInfo.Swap.Timeout1)
|
||||
@@ -244,7 +244,7 @@ func newSwapState(
|
||||
claimedWatcher := watcher.NewEventFilter(
|
||||
ctx,
|
||||
b.ETHClient().Raw(),
|
||||
b.ContractAddr(),
|
||||
b.SwapCreatorAddr(),
|
||||
ethStartNumber,
|
||||
claimedTopic,
|
||||
logClaimedCh,
|
||||
@@ -420,7 +420,7 @@ func (s *swapState) exit() 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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -561,7 +561,7 @@ func (s *swapState) approveToken() error {
|
||||
}
|
||||
|
||||
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 {
|
||||
return fmt.Errorf("failed to approve token: %w", err)
|
||||
}
|
||||
@@ -639,7 +639,7 @@ func (s *swapState) lockAsset() (*ethtypes.Receipt, error) {
|
||||
s.fundsLocked = true
|
||||
s.setTimeouts(t0, t1)
|
||||
|
||||
s.contractSwap = &contracts.SwapFactorySwap{
|
||||
s.contractSwap = &contracts.SwapCreatorSwap{
|
||||
Owner: s.ETHClient().Address(),
|
||||
Claimer: s.xmrmakerAddress,
|
||||
PubKeyClaim: cmtXMRMaker,
|
||||
@@ -655,7 +655,7 @@ func (s *swapState) lockAsset() (*ethtypes.Receipt, error) {
|
||||
StartNumber: receipt.BlockNumber,
|
||||
SwapID: s.contractSwapID,
|
||||
Swap: s.contractSwap,
|
||||
ContractAddress: s.Backend.ContractAddr(),
|
||||
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||
}
|
||||
|
||||
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.
|
||||
// If time t_0 has passed, there is no point of calling Ready().
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestSwapStateOngoing_handleEvent_EventXMRLocked(t *testing.T) {
|
||||
StartNumber: big.NewInt(int64(startNum)),
|
||||
SwapID: s.contractSwapID,
|
||||
Swap: s.contractSwap,
|
||||
ContractAddress: s.Backend.ContractAddr(),
|
||||
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||
}
|
||||
|
||||
ss, err := newSwapStateFromOngoing(
|
||||
@@ -89,7 +89,7 @@ func TestSwapStateOngoing_handleEvent_EventETHClaimed(t *testing.T) {
|
||||
StartNumber: big.NewInt(int64(startNum)),
|
||||
SwapID: s.contractSwapID,
|
||||
Swap: s.contractSwap,
|
||||
ContractAddress: s.Backend.ContractAddr(),
|
||||
SwapCreatorAddr: s.Backend.SwapCreatorAddr(),
|
||||
}
|
||||
|
||||
ss, err := newSwapStateFromOngoing(
|
||||
|
||||
@@ -90,8 +90,8 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
||||
txOpts, err := bind.NewKeyedTransactorWithChainID(pk, ec.ChainID())
|
||||
require.NoError(t, err)
|
||||
|
||||
var forwarderAddress ethcommon.Address
|
||||
_, tx, _, err := contracts.DeploySwapFactory(txOpts, ec.Raw(), forwarderAddress)
|
||||
var forwarderAddr ethcommon.Address
|
||||
_, tx, _, err := contracts.DeploySwapCreator(txOpts, ec.Raw(), forwarderAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
addr, err := bind.WaitDeployed(ctx, ec.Raw(), tx)
|
||||
@@ -108,14 +108,14 @@ func newBackendAndNet(t *testing.T) (backend.Backend, *mockNet) {
|
||||
|
||||
net := new(mockNet)
|
||||
bcfg := &backend.Config{
|
||||
Ctx: context.Background(),
|
||||
MoneroClient: monero.CreateWalletClient(t),
|
||||
EthereumClient: ec,
|
||||
Environment: common.Development,
|
||||
SwapManager: newSwapManager(t),
|
||||
SwapFactoryAddress: addr,
|
||||
Net: net,
|
||||
RecoveryDB: rdb,
|
||||
Ctx: ctx,
|
||||
MoneroClient: monero.CreateWalletClient(t),
|
||||
EthereumClient: ec,
|
||||
Environment: common.Development,
|
||||
SwapManager: newSwapManager(t),
|
||||
SwapCreatorAddr: addr,
|
||||
Net: net,
|
||||
RecoveryDB: rdb,
|
||||
}
|
||||
|
||||
b, err := backend.NewBackend(bcfg)
|
||||
@@ -241,7 +241,7 @@ func TestSwapState_HandleProtocolMessage_SendKeysMessage_Refund(t *testing.T) {
|
||||
}
|
||||
|
||||
// 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.Equal(t, contracts.StageCompleted, stage)
|
||||
}
|
||||
@@ -329,7 +329,7 @@ func TestSwapState_NotifyXMRLock_Refund(t *testing.T) {
|
||||
}
|
||||
|
||||
// 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.Equal(t, uint64(0), balance.Uint64())
|
||||
}
|
||||
@@ -429,7 +429,7 @@ func TestSwapState_ApproveToken(t *testing.T) {
|
||||
s, contract := newTestSwapStateWithERC20(t, initialBalance)
|
||||
err := s.approveToken()
|
||||
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.Equal(t, initialBalance, allowance)
|
||||
}
|
||||
|
||||
@@ -37,9 +37,9 @@ func CreateRelayClaimRequest(
|
||||
ctx context.Context,
|
||||
claimerEthKey *ecdsa.PrivateKey,
|
||||
ec *ethclient.Client,
|
||||
swapFactoryAddress ethcommon.Address,
|
||||
forwarderAddress ethcommon.Address,
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swapCreatorAddr ethcommon.Address,
|
||||
forwarderAddr ethcommon.Address,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret *[32]byte,
|
||||
) (*message.RelayClaimRequest, error) {
|
||||
|
||||
@@ -47,8 +47,8 @@ func CreateRelayClaimRequest(
|
||||
ctx,
|
||||
claimerEthKey,
|
||||
ec,
|
||||
swapFactoryAddress,
|
||||
forwarderAddress,
|
||||
swapCreatorAddr,
|
||||
forwarderAddr,
|
||||
swap,
|
||||
secret,
|
||||
)
|
||||
@@ -57,10 +57,10 @@ func CreateRelayClaimRequest(
|
||||
}
|
||||
|
||||
return &message.RelayClaimRequest{
|
||||
OfferID: nil, // set elsewhere if sending to counterparty
|
||||
SwapFactoryAddress: swapFactoryAddress,
|
||||
Swap: swap,
|
||||
Secret: secret[:],
|
||||
Signature: signature,
|
||||
OfferID: nil, // set elsewhere if sending to counterparty
|
||||
SwapCreatorAddr: swapCreatorAddr,
|
||||
Swap: swap,
|
||||
Secret: secret[:],
|
||||
Signature: signature,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -22,28 +22,28 @@ import (
|
||||
|
||||
// Speed up tests a little by giving deployContracts(...) a package-level cache.
|
||||
// These variables should not be accessed by other functions.
|
||||
var _forwarderAddress *ethcommon.Address
|
||||
var _swapFactoryAddress *ethcommon.Address
|
||||
var _forwarderAddr *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) {
|
||||
ctx := context.Background()
|
||||
|
||||
if _forwarderAddress == nil || _swapFactoryAddress == nil {
|
||||
if _forwarderAddr == nil || _swapCreatorAddr == nil {
|
||||
forwarderAddr, err := contracts.DeployGSNForwarderWithKey(ctx, ec, key)
|
||||
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)
|
||||
_swapFactoryAddress = &swapFactoryAddr
|
||||
_swapCreatorAddr = &swapCreatorAddr
|
||||
}
|
||||
|
||||
return *_swapFactoryAddress, *_forwarderAddress
|
||||
return *_swapCreatorAddr, *_forwarderAddr
|
||||
}
|
||||
|
||||
func createTestSwap(claimer ethcommon.Address) *contracts.SwapFactorySwap {
|
||||
return &contracts.SwapFactorySwap{
|
||||
func createTestSwap(claimer ethcommon.Address) *contracts.SwapCreatorSwap {
|
||||
return &contracts.SwapCreatorSwap{
|
||||
Owner: ethcommon.Address{0x1},
|
||||
Claimer: claimer,
|
||||
PubKeyClaim: [32]byte{0x1},
|
||||
@@ -62,16 +62,16 @@ func TestCreateRelayClaimRequest(t *testing.T) {
|
||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
secret := [32]byte{0x1}
|
||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
|
||||
// success path
|
||||
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.NotNil(t, req)
|
||||
|
||||
// change the ethkey to not match the claimer address to trigger the error path
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -23,9 +23,9 @@ func createForwarderSignature(
|
||||
ctx context.Context,
|
||||
claimerEthKey *ecdsa.PrivateKey,
|
||||
ec *ethclient.Client,
|
||||
swapFactoryAddress ethcommon.Address,
|
||||
forwarderAddress ethcommon.Address,
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swapCreatorAddr ethcommon.Address,
|
||||
forwarderAddr ethcommon.Address,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret *[32]byte,
|
||||
) ([]byte, error) {
|
||||
|
||||
@@ -33,7 +33,7 @@ func createForwarderSignature(
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func createForwarderSignature(
|
||||
|
||||
forwarderReq, err := createForwarderRequest(
|
||||
nonce,
|
||||
swapFactoryAddress,
|
||||
swapCreatorAddr,
|
||||
swap,
|
||||
secret,
|
||||
)
|
||||
@@ -69,8 +69,8 @@ func createForwarderSignature(
|
||||
// createForwarderRequest creates the forwarder request, which we sign the digest of.
|
||||
func createForwarderRequest(
|
||||
nonce *big.Int,
|
||||
swapFactoryAddress ethcommon.Address,
|
||||
swap *contracts.SwapFactorySwap,
|
||||
swapCreatorAddr ethcommon.Address,
|
||||
swap *contracts.SwapCreatorSwap,
|
||||
secret *[32]byte,
|
||||
) (*gsnforwarder.IForwarderForwardRequest, error) {
|
||||
|
||||
@@ -81,7 +81,7 @@ func createForwarderRequest(
|
||||
|
||||
req := &gsnforwarder.IForwarderForwardRequest{
|
||||
From: swap.Claimer,
|
||||
To: swapFactoryAddress,
|
||||
To: swapCreatorAddr,
|
||||
Value: big.NewInt(0),
|
||||
Gas: big.NewInt(relayedClaimGas),
|
||||
Nonce: nonce,
|
||||
@@ -93,28 +93,28 @@ func createForwarderRequest(
|
||||
}
|
||||
|
||||
// getClaimRelayerTxCalldata returns the call data to be used when invoking the
|
||||
// claimRelayer method on the SwapFactory contract.
|
||||
func getClaimRelayerTxCalldata(feeWei *big.Int, swap *contracts.SwapFactorySwap, secret *[32]byte) ([]byte, error) {
|
||||
return contracts.SwapFactoryParsedABI.Pack("claimRelayer", *swap, *secret, feeWei)
|
||||
// claimRelayer method on the SwapCreator contract.
|
||||
func getClaimRelayerTxCalldata(feeWei *big.Int, swap *contracts.SwapCreatorSwap, secret *[32]byte) ([]byte, error) {
|
||||
return contracts.SwapCreatorParsedABI.Pack("claimRelayer", *swap, *secret, feeWei)
|
||||
}
|
||||
|
||||
func getForwarderAndDomainSeparator(
|
||||
ctx context.Context,
|
||||
ec *ethclient.Client,
|
||||
forwarderAddress ethcommon.Address,
|
||||
forwarderAddr ethcommon.Address,
|
||||
) (*gsnforwarder.Forwarder, *[32]byte, error) {
|
||||
chainID, err := ec.ChainID(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
forwarder, err := gsnforwarder.NewForwarder(forwarderAddress, ec)
|
||||
forwarder, err := gsnforwarder.NewForwarder(forwarderAddr, ec)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
domainSeparator, err := rcommon.GetEIP712DomainSeparator(gsnforwarder.DefaultName,
|
||||
gsnforwarder.DefaultVersion, chainID, forwarderAddress)
|
||||
gsnforwarder.DefaultVersion, chainID, forwarderAddr)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to get EIP712 domain separator: %w", err)
|
||||
}
|
||||
|
||||
@@ -33,12 +33,12 @@ func ValidateAndSendTransaction(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reqSwapFactory, err := contracts.NewSwapFactory(req.SwapFactoryAddress, ec.Raw())
|
||||
reqSwapCreator, err := contracts.NewSwapCreator(req.SwapCreatorAddr, ec.Raw())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reqForwarderAddr, err := reqSwapFactory.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||
reqForwarderAddr, err := reqSwapCreator.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func ValidateAndSendTransaction(
|
||||
// The size of request.Secret was vetted when it was deserialized
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func validateClaimRequest(
|
||||
}
|
||||
|
||||
// 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
|
||||
// 3. the swap value is strictly greater than the relayer fee
|
||||
// 4. TODO: Validate that the swap exists and is in a claimable state?
|
||||
@@ -41,19 +41,19 @@ func validateClaimValues(
|
||||
ctx context.Context,
|
||||
request *message.RelayClaimRequest,
|
||||
ec *ethclient.Client,
|
||||
ourSwapFactoryAddr ethcommon.Address,
|
||||
ourSwapCreatorAddr ethcommon.Address,
|
||||
) error {
|
||||
isTakerRelay := request.OfferID != nil
|
||||
|
||||
// Validate the deployed SwapFactory contract, if it is not at the same address
|
||||
// as our own. The CheckSwapFactoryContractCode method validates both the
|
||||
// SwapFactory bytecode and the Forwarder bytecode.
|
||||
if request.SwapFactoryAddress != ourSwapFactoryAddr {
|
||||
// Validate the deployed SwapCreator contract, if it is not at the same address
|
||||
// as our own. The CheckSwapCreatorContractCode method validates both the
|
||||
// SwapCreator bytecode and the Forwarder bytecode.
|
||||
if request.SwapCreatorAddr != ourSwapCreatorAddr {
|
||||
if isTakerRelay {
|
||||
return fmt.Errorf("taker claim swap factory mismatch found=%s expected=%s",
|
||||
request.SwapFactoryAddress, ourSwapFactoryAddr)
|
||||
return fmt.Errorf("taker claim swap creator mismatch found=%s expected=%s",
|
||||
request.SwapCreatorAddr, ourSwapCreatorAddr)
|
||||
}
|
||||
_, err := contracts.CheckSwapFactoryContractCode(ctx, ec, request.SwapFactoryAddress)
|
||||
_, err := contracts.CheckSwapCreatorContractCode(ctx, ec, request.SwapCreatorAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -85,12 +85,12 @@ func validateClaimSignature(
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
forwarderAddr, err := swapFactory.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||
forwarderAddr, err := swapCreator.TrustedForwarder(&bind.CallOpts{Context: ctx})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func validateClaimSignature(
|
||||
|
||||
forwarderRequest, err := createForwarderRequest(
|
||||
nonce,
|
||||
request.SwapFactoryAddress,
|
||||
request.SwapCreatorAddr,
|
||||
request.Swap,
|
||||
secret,
|
||||
)
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestValidateRelayerFee(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
key := tests.GetTakerTestKey(t)
|
||||
swapFactoryAddr, _ := deployContracts(t, ec, key)
|
||||
swapCreatorAddr, _ := deployContracts(t, ec, key)
|
||||
|
||||
type testCase struct {
|
||||
description string
|
||||
@@ -50,7 +50,7 @@ func TestValidateRelayerFee(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
swap := &contracts.SwapFactorySwap{
|
||||
swap := &contracts.SwapCreatorSwap{
|
||||
Owner: ethcommon.Address{},
|
||||
Claimer: ethcommon.Address{},
|
||||
PubKeyClaim: [32]byte{},
|
||||
@@ -63,12 +63,12 @@ func TestValidateRelayerFee(t *testing.T) {
|
||||
}
|
||||
|
||||
request := &message.RelayClaimRequest{
|
||||
SwapFactoryAddress: swapFactoryAddr,
|
||||
Swap: swap,
|
||||
Secret: make([]byte, 32),
|
||||
SwapCreatorAddr: swapCreatorAddr,
|
||||
Swap: swap,
|
||||
Secret: make([]byte, 32),
|
||||
}
|
||||
|
||||
err := validateClaimValues(ctx, request, ec, swapFactoryAddr)
|
||||
err := validateClaimValues(ctx, request, ec, swapCreatorAddr)
|
||||
if tc.expectErr != "" {
|
||||
require.ErrorContains(t, err, tc.expectErr, tc.description)
|
||||
} else {
|
||||
@@ -82,18 +82,18 @@ func TestValidateRelayerFee(t *testing.T) {
|
||||
// the taker who is being asked to claim.
|
||||
func Test_validateClaimValues_takerClaim_contractAddressNotEqualFail(t *testing.T) {
|
||||
offerID := types.Hash{0x1} // non-nil offer ID passed to indicate taker claim
|
||||
swapFactoryAddrInClaim := ethcommon.Address{0x1} // address in claim
|
||||
swapFactoryAddrOurs := ethcommon.Address{0x2} // passed to validateClaimValues
|
||||
swapCreatorAddrInClaim := ethcommon.Address{0x1} // address in claim
|
||||
swapCreatorAddrOurs := ethcommon.Address{0x2} // passed to validateClaimValues
|
||||
|
||||
request := &message.RelayClaimRequest{
|
||||
OfferID: &offerID,
|
||||
SwapFactoryAddress: swapFactoryAddrInClaim,
|
||||
Secret: make([]byte, 32),
|
||||
Swap: new(contracts.SwapFactorySwap), // test fails before we validate this
|
||||
OfferID: &offerID,
|
||||
SwapCreatorAddr: swapCreatorAddrInClaim,
|
||||
Secret: make([]byte, 32),
|
||||
Swap: new(contracts.SwapCreatorSwap), // test fails before we validate this
|
||||
}
|
||||
|
||||
err := validateClaimValues(context.Background(), request, nil, swapFactoryAddrOurs)
|
||||
require.ErrorContains(t, err, "taker claim swap factory mismatch")
|
||||
err := validateClaimValues(context.Background(), request, nil, swapCreatorAddrOurs)
|
||||
require.ErrorContains(t, err, "taker claim swap creator mismatch")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
key := tests.GetTakerTestKey(t)
|
||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, key)
|
||||
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, key)
|
||||
|
||||
request := &message.RelayClaimRequest{
|
||||
OfferID: nil, // DHT relayer claim
|
||||
SwapFactoryAddress: forwarderAddr, // not a valid swap factory contract
|
||||
Secret: make([]byte, 32),
|
||||
Swap: new(contracts.SwapFactorySwap), // test fails before we validate this
|
||||
OfferID: nil, // DHT relayer claim
|
||||
SwapCreatorAddr: forwarderAddr, // not a valid swap creator contract
|
||||
Secret: make([]byte, 32),
|
||||
Swap: new(contracts.SwapCreatorSwap), // test fails before we validate this
|
||||
}
|
||||
|
||||
err := validateClaimValues(context.Background(), request, ec, swapFactoryAddr)
|
||||
require.ErrorContains(t, err, "contract address does not contain correct SwapFactory code")
|
||||
err := validateClaimValues(context.Background(), request, ec, swapCreatorAddr)
|
||||
require.ErrorContains(t, err, "contract address does not contain correct SwapCreator code")
|
||||
}
|
||||
|
||||
func Test_validateSignature(t *testing.T) {
|
||||
@@ -121,10 +121,10 @@ func Test_validateSignature(t *testing.T) {
|
||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
secret := [32]byte{0x1}
|
||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
|
||||
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)
|
||||
|
||||
// success path
|
||||
@@ -143,19 +143,19 @@ func Test_validateClaimRequest(t *testing.T) {
|
||||
claimer := crypto.PubkeyToAddress(*ethKey.Public().(*ecdsa.PublicKey))
|
||||
ec, _ := tests.NewEthClient(t)
|
||||
secret := [32]byte{0x1}
|
||||
swapFactoryAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
swapCreatorAddr, forwarderAddr := deployContracts(t, ec, ethKey)
|
||||
|
||||
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)
|
||||
|
||||
// success path
|
||||
err = validateClaimRequest(ctx, req, ec, swapFactoryAddr)
|
||||
err = validateClaimRequest(ctx, req, ec, swapCreatorAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
// test failure path by passing a non-eth asset
|
||||
asset := ethcommon.Address{0x1}
|
||||
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)))
|
||||
}
|
||||
|
||||
@@ -120,6 +120,10 @@ func (s *Server) WsURL() string {
|
||||
|
||||
// Start starts the JSON-RPC and Websocket server.
|
||||
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 websockets server on %s", s.WsURL())
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ compile-contract() {
|
||||
--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 IERC20Metadata IERC20 ierc20
|
||||
compile-contract AggregatorV3Interface AggregatorV3Interface aggregator_v3_interface
|
||||
|
||||
@@ -106,9 +106,9 @@ start-daemons() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SWAP_FACTORY_ADDR="$(jq -r .swapFactory "${CONTRACT_ADDR_FILE}")"
|
||||
FORWARDER_ADDR="$(jq -r .forwarder "${CONTRACT_ADDR_FILE}")"
|
||||
if [[ -z "${SWAP_FACTORY_ADDR}" ]] || [[ -z "${FORWARDER_ADDR}" ]]; then
|
||||
SWAP_CREATOR_ADDR="$(jq -r .swapCreatorAddr "${CONTRACT_ADDR_FILE}")"
|
||||
FORWARDER_ADDR="$(jq -r .forwarderAddr "${CONTRACT_ADDR_FILE}")"
|
||||
if [[ -z "${SWAP_CREATOR_ADDR}" ]] || [[ -z "${FORWARDER_ADDR}" ]]; then
|
||||
echo "Failed to get Alice's deployed contract addresses"
|
||||
stop-daemons
|
||||
exit 1
|
||||
@@ -120,14 +120,14 @@ start-daemons() {
|
||||
"--data-dir=${SWAP_TEST_DATA_DIR}/bob" \
|
||||
--libp2p-port=9944 \
|
||||
"--bootnodes=${ALICE_MULTIADDR}" \
|
||||
"--contract-address=${SWAP_FACTORY_ADDR}"
|
||||
"--contract-address=${SWAP_CREATOR_ADDR}"
|
||||
|
||||
start-swapd charlie "${CHARLIE_RPC_PORT}" \
|
||||
"--log-level=${LOG_LEVEL}" \
|
||||
--data-dir "${SWAP_TEST_DATA_DIR}/charlie" \
|
||||
--libp2p-port=9955 \
|
||||
"--bootnodes=${ALICE_MULTIADDR}" \
|
||||
"--contract-address=${SWAP_FACTORY_ADDR}" \
|
||||
"--contract-address=${SWAP_CREATOR_ADDR}" \
|
||||
"--relayer"
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ stop-daemons() {
|
||||
echo "running integration tests..."
|
||||
create-eth-keys
|
||||
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="${?}"
|
||||
KEEP_TEST_DATA="${OK}" stop-daemons
|
||||
|
||||
|
||||
Reference in New Issue
Block a user