Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DNM] Bridge endpoint consolidation [SLT-453] #3371

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 44 additions & 18 deletions packages/rest-api/src/controllers/bridgeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,16 @@ export const bridgeController = async (req, res) => {
fromToken,
toToken,
originUserAddress,
} = req.query
destAddress, // Optional parameter
} = req.query as {
fromChain: string
toChain: string
amount: string
fromToken: string
toToken: string
originUserAddress?: string
destAddress?: string
}

const fromTokenInfo = tokenAddressToToken(fromChain.toString(), fromToken)
const toTokenInfo = tokenAddressToToken(toChain.toString(), toToken)
Expand All @@ -37,23 +46,40 @@ export const bridgeController = async (req, res) => {
: {}
)

const payload = resp.map((quote) => {
const originQueryTokenOutInfo = tokenAddressToToken(
fromChain.toString(),
quote.originQuery.tokenOut
)
return {
...quote,
maxAmountOutStr: formatBNToString(
quote.maxAmountOut,
toTokenInfo.decimals
),
bridgeFeeFormatted: formatBNToString(
quote.feeAmount,
originQueryTokenOutInfo.decimals
),
}
})
const payload = await Promise.all(
resp.map(async (quote) => {
const originQueryTokenOutInfo = tokenAddressToToken(
fromChain.toString(),
quote.originQuery.tokenOut
)

const callData = destAddress
? await Synapse.bridge(
destAddress,
quote.routerAddress,
Number(fromChain),
Number(toChain),
fromToken,
amountInWei,
quote.originQuery,
quote.destQuery
)
: null

Comment on lines +56 to +68
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for Synapse.bridge call

The Synapse.bridge call could fail independently, but there's no specific error handling for this operation. This could lead to unclear error messages or unhandled promise rejections.

Consider wrapping the bridge call in a try-catch:

-        const callData = destAddress
-          ? await Synapse.bridge(
+        const callData = destAddress ? await (async () => {
+          try {
+            return await Synapse.bridge(
              destAddress,
              quote.routerAddress,
              Number(fromChain),
              Number(toChain),
              fromToken,
              amountInWei,
              quote.originQuery,
              quote.destQuery
-            )
+            )
+          } catch (error) {
+            logger.error('Failed to generate bridge call data', {
+              destAddress,
+              error: error.message,
+            });
+            return null;
+          }
+        })()
          : null
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const callData = destAddress
? await Synapse.bridge(
destAddress,
quote.routerAddress,
Number(fromChain),
Number(toChain),
fromToken,
amountInWei,
quote.originQuery,
quote.destQuery
)
: null
const callData = destAddress ? await (async () => {
try {
return await Synapse.bridge(
destAddress,
quote.routerAddress,
Number(fromChain),
Number(toChain),
fromToken,
amountInWei,
quote.originQuery,
quote.destQuery
)
} catch (error) {
logger.error('Failed to generate bridge call data', {
destAddress,
error: error.message,
});
return null;
}
})()
: null

return {
...quote,
maxAmountOutStr: formatBNToString(
quote.maxAmountOut,
toTokenInfo.decimals
),
bridgeFeeFormatted: formatBNToString(
quote.feeAmount,
originQueryTokenOutInfo.decimals
),
callData,
}
})
)

logger.info(`Successful bridgeController response`, {
payload,
Expand Down
13 changes: 12 additions & 1 deletion packages/rest-api/src/controllers/swapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const swapController = async (req, res) => {
return res.status(400).json({ errors: errors.array() })
}
try {
const { chain, amount, fromToken, toToken } = req.query
const { chain, amount, fromToken, toToken, address } = req.query
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add address parameter validation

The new address parameter needs proper validation to prevent potential security issues. Consider adding validation using express-validator to ensure it's a valid Ethereum address.

Add this validation to your route configuration:

check('address')
  .optional()
  .isString()
  .custom((value) => isAddress(value))
  .withMessage('Invalid Ethereum address format'),


const fromTokenInfo = tokenAddressToToken(chain.toString(), fromToken)
const toTokenInfo = tokenAddressToToken(chain.toString(), toToken)
Expand All @@ -30,9 +30,20 @@ export const swapController = async (req, res) => {
toTokenInfo.decimals
)

const callData = address
? await Synapse.swap(
Number(chain),
address,
fromToken,
amountInWei,
quote.query
)
: null
Comment on lines +33 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance error handling for swap operation

The conditional swap operation needs specific error handling to distinguish between different failure modes (e.g., invalid address, insufficient funds, network issues).

Consider wrapping the swap call in a try-catch block with specific error types:

let callData = null;
if (address) {
  try {
    callData = await Synapse.swap(
      Number(chain),
      address,
      fromToken,
      amountInWei,
      quote.query
    );
  } catch (error) {
    if (error instanceof InvalidAddressError) {
      throw new Error('Invalid address provided');
    }
    // Handle other specific error cases
    throw error;
  }
}


const payload = {
...quote,
maxAmountOut: formattedMaxAmountOut,
callData,
}

logger.info(`Successful swapController response`, {
Expand Down
20 changes: 20 additions & 0 deletions packages/rest-api/src/routes/bridgeRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ const router: express.Router = express.Router()
* schema:
* type: string
* description: The address of the user on the origin chain
* - in: query
* name: destAddress
* required: false
* schema:
* type: string
* description: The destination address for the bridge transaction
* responses:
* 200:
* description: Successful response
Expand Down Expand Up @@ -101,6 +107,16 @@ const router: express.Router = express.Router()
* type: string
* bridgeFeeFormatted:
* type: string
* callData:
* type: object
* nullable: true
* properties:
* to:
* type: string
* data:
* type: string
* value:
* type: string
* example:
* - id: "01920c87-7f14-7cdf-90e1-e13b2d4af55f"
* feeAmount:
Expand Down Expand Up @@ -239,6 +255,10 @@ router.get(
.optional()
.custom((value) => isAddress(value))
.withMessage('Invalid originUserAddress address'),
check('destAddress')
.optional()
.custom((value) => isAddress(value))
.withMessage('Invalid destAddress'),
],
showFirstValidationError,
bridgeController
Expand Down
21 changes: 21 additions & 0 deletions packages/rest-api/src/routes/swapRoute.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import express from 'express'
import { check } from 'express-validator'
import { isAddress } from 'ethers/lib/utils'

import { showFirstValidationError } from '../middleware/showFirstValidationError'
import { swapController } from '../controllers/swapController'
Expand Down Expand Up @@ -44,6 +45,12 @@ const router: express.Router = express.Router()
* schema:
* type: number
* description: The amount of tokens to swap
* - in: query
* name: address
* required: false
* schema:
* type: string
* description: Optional. The address that will perform the swap. If provided, returns transaction data.
* responses:
* 200:
* description: Successful response
Expand Down Expand Up @@ -74,6 +81,16 @@ const router: express.Router = express.Router()
* rawParams:
* type: string
* description: Raw parameters for the swap
* callData:
* type: object
* nullable: true
* properties:
* to:
* type: string
* data:
* type: string
* value:
* type: string
* example:
* routerAddress: "0x7E7A0e201FD38d3ADAA9523Da6C109a07118C96a"
* maxAmountOut: "999.746386"
Expand Down Expand Up @@ -176,6 +193,10 @@ router.get(
return validSwapTokens(chain, fromToken, toToken)
})
.withMessage('Swap not supported for given tokens'),
check('address')
.optional()
.custom((value) => isAddress(value))
.withMessage('Invalid address'),
],
showFirstValidationError,
swapController
Expand Down
48 changes: 48 additions & 0 deletions packages/rest-api/src/tests/bridgeRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,52 @@ describe('Bridge Route with Real Synapse Service', () => {
expect(response.status).toBe(400)
expect(response.body.error).toHaveProperty('field', 'amount')
})

it('should return bridge quotes with callData when destAddress is provided', async () => {
const response = await request(app).get('/bridge').query({
fromChain: '1',
toChain: '10',
fromToken: USDC.addresses[1],
toToken: USDC.addresses[10],
amount: '1000',
destAddress: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
})

expect(response.status).toBe(200)
expect(Array.isArray(response.body)).toBe(true)
expect(response.body.length).toBeGreaterThan(0)
expect(response.body[0]).toHaveProperty('callData')
expect(response.body[0].callData).toHaveProperty('to')
expect(response.body[0].callData).toHaveProperty('data')
expect(response.body[0].callData).toHaveProperty('value')
}, 15000)

it('should return bridge quotes without callData when destAddress is not provided', async () => {
const response = await request(app).get('/bridge').query({
fromChain: '1',
toChain: '10',
fromToken: USDC.addresses[1],
toToken: USDC.addresses[10],
amount: '1000',
})

expect(response.status).toBe(200)
expect(Array.isArray(response.body)).toBe(true)
expect(response.body.length).toBeGreaterThan(0)
expect(response.body[0].callData).toBeNull()
}, 15000)

it('should return 400 for invalid destAddress', async () => {
const response = await request(app).get('/bridge').query({
fromChain: '1',
toChain: '10',
fromToken: USDC.addresses[1],
toToken: USDC.addresses[10],
amount: '1000',
destAddress: 'invalid_address',
})

expect(response.status).toBe(400)
expect(response.body.error).toHaveProperty('message', 'Invalid destAddress')
}, 15000)
})
47 changes: 47 additions & 0 deletions packages/rest-api/src/tests/swapRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,51 @@ describe('Swap Route with Real Synapse Service', () => {
expect(response.status).toBe(400)
expect(response.body.error).toHaveProperty('field', 'amount')
}, 10_000)

it('should return swap quote with callData when address is provided', async () => {
const response = await request(app).get('/swap').query({
chain: '1',
fromToken: USDC.addresses[1],
toToken: DAI.addresses[1],
amount: '1000',
address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
})

expect(response.status).toBe(200)
expect(response.body).toHaveProperty('maxAmountOut')
expect(response.body).toHaveProperty('routerAddress')
expect(response.body).toHaveProperty('query')
expect(response.body).toHaveProperty('callData')
expect(response.body.callData).toHaveProperty('to')
expect(response.body.callData).toHaveProperty('data')
expect(response.body.callData).toHaveProperty('value')
}, 10_000)

it('should return swap quote without callData when address is not provided', async () => {
const response = await request(app).get('/swap').query({
chain: '1',
fromToken: USDC.addresses[1],
toToken: DAI.addresses[1],
amount: '1000',
})

expect(response.status).toBe(200)
expect(response.body).toHaveProperty('maxAmountOut')
expect(response.body).toHaveProperty('routerAddress')
expect(response.body).toHaveProperty('query')
expect(response.body.callData).toBeNull()
}, 10_000)

it('should return 400 for invalid address', async () => {
const response = await request(app).get('/swap').query({
chain: '1',
fromToken: USDC.addresses[1],
toToken: DAI.addresses[1],
amount: '1000',
address: 'invalid_address',
})

expect(response.status).toBe(400)
expect(response.body.error).toHaveProperty('message', 'Invalid address')
}, 10_000)
})
18 changes: 18 additions & 0 deletions packages/rest-api/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@
"type": "string"
},
"description": "The address of the user on the origin chain"
},
{
"in": "query",
"name": "destAddress",
"required": true,
"schema": {
"type": "string"
},
"description": "The destination address of the user on the destination chain"
Comment on lines +200 to +208
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add address validation patterns for security.

Consider adding regex patterns to validate Ethereum addresses, preventing invalid inputs and potential security issues.

 {
   "in": "query",
   "name": "destAddress",
   "required": true,
   "schema": {
-    "type": "string"
+    "type": "string",
+    "pattern": "^0x[a-fA-F0-9]{40}$",
+    "minLength": 42,
+    "maxLength": 42
   },
   "description": "The destination address of the user on the destination chain"
 }

Also applies to: 1218-1226

}
],
"responses": {
Expand Down Expand Up @@ -1206,6 +1215,15 @@
"type": "number"
},
"description": "The amount of tokens to swap"
},
{
"in": "query",
"name": "address",
"required": true,
"schema": {
"type": "string"
},
"description": "The address of the user"
}
],
"responses": {
Expand Down
Loading