Skip to content

Commit

Permalink
chore(example): update examples with better logs and validations
Browse files Browse the repository at this point in the history
  • Loading branch information
RanGojo committed Sep 14, 2024
1 parent c06b0eb commit ad9c044
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 50 deletions.
13 changes: 8 additions & 5 deletions examples/basic/node-evm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import { findToken } from '../shared/utils/meta.js'
import { logMeta, logSelectedTokens, logQuote, logWallet, logSwap, logSwapStatus, logTransactionHash, logApprovalResponse } from "../shared/utils/logger.js";
import { TransactionRequest, ethers } from "ethers";
import { setTimeout } from 'timers/promises'
import { getRpcUrlForBlockchain } from "./rpc.js";

// setup wallet & RPC provider
// please change rpc provider url if you want to test another chain rather than BSC
// setup wallet
const privateKey = 'YOUR_PRIVATE_KEY';
const wallet = new ethers.Wallet(privateKey);
const rpcProvider = new ethers.JsonRpcProvider('https://bsc-dataseed1.defibit.io');
const walletWithProvider = wallet.connect(rpcProvider);
logWallet(walletWithProvider.address)

logWallet(wallet.address)

// initiate sdk using your api key
const API_KEY = "c6381a79-2817-4602-83bf-6a641a409e32"
Expand Down Expand Up @@ -61,6 +60,10 @@ if (!tx) {
}

if (tx.type === TransactionType.EVM) {
// set rpc provider
const rpcProvider = new ethers.JsonRpcProvider(getRpcUrlForBlockchain(meta, tx.blockChain.name));
const walletWithProvider = wallet.connect(rpcProvider);

if (tx.approveData && tx.approveTo) {
// sign the approve transaction
const approveTransaction: TransactionRequest = {
Expand Down
2 changes: 1 addition & 1 deletion examples/basic/node-evm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "module",
"dependencies": {
"ethers": "^6.13.2",
"rango-sdk-basic": "^0.1.54"
"rango-sdk-basic": "^0.1.56"
},
"devDependencies": {
"tsx": "^4.17.0"
Expand Down
13 changes: 13 additions & 0 deletions examples/basic/node-evm/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { MetaResponse, TransactionType } from "rango-sdk-basic";

export function getRpcUrlForBlockchain(meta: MetaResponse, blockchainName: string): string {
const rpcUrl = meta
.blockchains
.filter(blockchain => blockchain.type === TransactionType.EVM)
.find(blockchain => blockchain.name === blockchainName)
?.info.rpcUrls?.[0]
if (!rpcUrl) {
throw new Error(`There is no rpc url for blockchain ${blockchainName}`)
}
return rpcUrl
}
18 changes: 9 additions & 9 deletions examples/basic/node-evm/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ asynckit@^0.4.0:
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==

axios@^1.7.3:
version "1.7.3"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.3.tgz#a1125f2faf702bc8e8f2104ec3a76fab40257d85"
integrity sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==
axios@^1.7.4:
version "1.7.7"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f"
integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
Expand Down Expand Up @@ -261,12 +261,12 @@ proxy-from-env@^1.1.0:
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==

rango-sdk-basic@^0.1.54:
version "0.1.54"
resolved "https://registry.yarnpkg.com/rango-sdk-basic/-/rango-sdk-basic-0.1.54.tgz#df24829d86a228bee04ba485c08df227a89d61b0"
integrity sha512-86i6atexhwGT+9plQ4Xyzvn4SftvZzFOfeknkISVQaISrxIuSfAnVg/R2LjKwpUOIpjN3DdF05XFp3GmQmWEng==
rango-sdk-basic@^0.1.56:
version "0.1.56"
resolved "https://registry.yarnpkg.com/rango-sdk-basic/-/rango-sdk-basic-0.1.56.tgz#4554ce94e144d604cf71f0c5937a561161bd0a6b"
integrity sha512-To6dk+g0TiIgYfIkpGf3zm/Y+3JksTS5yO9GhUl+c1RT1PEG4EqicnS+IIyI1xP2X7y7ZNZVPzinVMZCdptoqA==
dependencies:
axios "^1.7.3"
axios "^1.7.4"
rango-types "^0.1.73"
uuid-random "^1.3.2"

Expand Down
2 changes: 1 addition & 1 deletion examples/basic/node-solana/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"@rango-dev/signer-solana": "^0.31.0",
"@solana/web3.js": "^1.91.4",
"bs58": "^6.0.0",
"rango-sdk-basic": "^0.1.54"
"rango-sdk-basic": "^0.1.56"
},
"devDependencies": {
"tsx": "^4.17.0"
Expand Down
18 changes: 9 additions & 9 deletions examples/basic/node-solana/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,10 @@ asynckit@^0.4.0:
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==

axios@^1.7.3:
version "1.7.3"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.3.tgz#a1125f2faf702bc8e8f2104ec3a76fab40257d85"
integrity sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==
axios@^1.7.4:
version "1.7.7"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f"
integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
Expand Down Expand Up @@ -528,12 +528,12 @@ proxy-from-env@^1.1.0:
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==

rango-sdk-basic@^0.1.54:
version "0.1.54"
resolved "https://registry.yarnpkg.com/rango-sdk-basic/-/rango-sdk-basic-0.1.54.tgz#df24829d86a228bee04ba485c08df227a89d61b0"
integrity sha512-86i6atexhwGT+9plQ4Xyzvn4SftvZzFOfeknkISVQaISrxIuSfAnVg/R2LjKwpUOIpjN3DdF05XFp3GmQmWEng==
rango-sdk-basic@^0.1.56:
version "0.1.56"
resolved "https://registry.yarnpkg.com/rango-sdk-basic/-/rango-sdk-basic-0.1.56.tgz#4554ce94e144d604cf71f0c5937a561161bd0a6b"
integrity sha512-To6dk+g0TiIgYfIkpGf3zm/Y+3JksTS5yO9GhUl+c1RT1PEG4EqicnS+IIyI1xP2X7y7ZNZVPzinVMZCdptoqA==
dependencies:
axios "^1.7.3"
axios "^1.7.4"
rango-types "^0.1.73"
uuid-random "^1.3.2"

Expand Down
4 changes: 2 additions & 2 deletions examples/basic/shared/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ export function logSwapStatus(state: StatusResponse) {

export function logTransactionHash(hash: string, isApproval: boolean) {
if (isApproval) {
console.log(`- approve transaction hash: ${hash}`)
console.log(`- sending approve transaction: ${hash}`)
} else {
console.log(`- main transaction hash: ${hash}`)
console.log(`- sending main transaction: ${hash}`)
}
}

Expand Down
34 changes: 25 additions & 9 deletions examples/main/node-evm/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
// run `node --import=tsx index.ts` in the terminal

import { CreateTransactionRequest, RangoClient, TransactionStatus, TransactionType } from "rango-sdk";
import { CreateTransactionRequest, MultiRouteRequest, RangoClient, TransactionStatus, TransactionType } from "rango-sdk";
import { findToken } from '../shared/utils/meta.js'
import { logMeta, logSelectedTokens, logWallet, logTransactionHash, logApprovalResponse, logRoutes, logStepStatus, logConfirmedRoute, logRouteStep } from "../shared/utils/logger.js";
import { TransactionRequest, ethers } from "ethers";
import { setTimeout } from 'timers/promises'
import { getRpcUrlForBlockchain } from "./rpc.js";

// setup wallet & RPC provider
// please change rpc provider url if you want to test another chain rather than BSC
// setup wallet
const privateKey = 'YOUR_PRIVATE_KEY';
const wallet = new ethers.Wallet(privateKey);
const rpcProvider = new ethers.JsonRpcProvider('https://bsc-dataseed1.defibit.io');
const walletWithProvider = wallet.connect(rpcProvider);
const waleltAddress = walletWithProvider.address
const waleltAddress = wallet.address
logWallet(waleltAddress)

// initiate sdk using your api key
Expand All @@ -26,7 +24,7 @@ logMeta(meta)
// some example tokens for test purpose
const sourceBlockchain = "BSC"
const sourceTokenAddress = "0x55d398326f99059ff775485246999027b3197955"
const targetBlockchain = "BSC"
const targetBlockchain = "AVAX_CCHAIN"
const targetTokenAddress = null
const amount = "0.001"

Expand All @@ -36,18 +34,19 @@ const targetToken = findToken(meta.tokens, targetBlockchain, targetTokenAddress)
logSelectedTokens(sourceToken, targetToken)

// get route
const routingRequest = {
const routingRequest: MultiRouteRequest = {
from: sourceToken,
to: targetToken,
amount,
slippage: '1.0',
transactionTypes: [TransactionType.EVM]
}
const routingResponse = await rango.getAllRoutes(routingRequest)

logRoutes(routingResponse)

if (routingResponse.results.length === 0) {
throw new Error(`There was no route! ${routingResponse.error}`)
throw new Error(`No routes found! ${routingResponse.error}`)
}

// confirm one of the routes
Expand Down Expand Up @@ -75,11 +74,28 @@ if (!confirmedRoute) {

logConfirmedRoute(confirmedRoute)

// check wallet to have enough balance or fee using confirm response
for (const validation of confirmedRoute?.validationStatus || []) {
for (const wallet of validation.wallets) {
for (const asset of wallet.requiredAssets) {
if (!asset.ok) {
const message = `Insufficient ${asset.reason}: asset: ${asset.asset.blockchain}.${asset.asset.symbol},
required balance: ${asset.requiredAmount.amount}, current balance: ${asset.currentAmount.amount}`
throw new Error(message)
}
}
}
}

let step = 1
const swapSteps = confirmedRoute.result?.swaps || []
for (const swap of swapSteps) {
logRouteStep(swap, step)

// set rpc provider for this step
const rpcProvider = new ethers.JsonRpcProvider(getRpcUrlForBlockchain(meta, swap.from.blockchain));
const walletWithProvider = wallet.connect(rpcProvider);

const request: CreateTransactionRequest = {
requestId: confirmedRoute.requestId,
step: step,
Expand Down
2 changes: 1 addition & 1 deletion examples/main/node-evm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "module",
"dependencies": {
"ethers": "^6.13.2",
"rango-sdk": "^0.1.54"
"rango-sdk": "^0.1.56"
},
"devDependencies": {
"tsx": "^4.17.0"
Expand Down
13 changes: 13 additions & 0 deletions examples/main/node-evm/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { MetaResponse, TransactionType } from "rango-sdk";

export function getRpcUrlForBlockchain(meta: MetaResponse, blockchainName: string): string {
const rpcUrl = meta
.blockchains
.filter(blockchain => blockchain.type === TransactionType.EVM)
.find(blockchain => blockchain.name === blockchainName)
?.info.rpcUrls?.[0]
if (!rpcUrl) {
throw new Error(`There is no rpc url for blockchain ${blockchainName}`)
}
return rpcUrl
}
18 changes: 9 additions & 9 deletions examples/main/node-evm/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ asynckit@^0.4.0:
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==

axios@^1.7.3:
version "1.7.3"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.3.tgz#a1125f2faf702bc8e8f2104ec3a76fab40257d85"
integrity sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==
axios@^1.7.4:
version "1.7.7"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f"
integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
Expand Down Expand Up @@ -261,12 +261,12 @@ proxy-from-env@^1.1.0:
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==

rango-sdk@^0.1.54:
version "0.1.54"
resolved "https://registry.yarnpkg.com/rango-sdk/-/rango-sdk-0.1.54.tgz#8869b5237ffa6f8c028c4e38652ba05aff480784"
integrity sha512-A8y6ZJJd6HycHBF41EyAsUrZ+Mq5UTCyUrJ3vZYY5eU+bVPZ+pOPSvCfQ2T1GL6w0UEm/Btj8uNhdcbmSTnUKA==
rango-sdk@^0.1.56:
version "0.1.56"
resolved "https://registry.yarnpkg.com/rango-sdk/-/rango-sdk-0.1.56.tgz#02ff80ae45563b5f1fc577e8c03f1114dc4ae333"
integrity sha512-EMQKqiKO5iKDTwPviFtreawKwN/l5NGJhzOwIlrnIIXrA1fH7qtsxO/ioZ0w1UPtrpx1dg7gwuonDntMrG4+DA==
dependencies:
axios "^1.7.3"
axios "^1.7.4"
rango-types "^0.1.73"
uuid-random "^1.3.2"

Expand Down
8 changes: 4 additions & 4 deletions examples/main/shared/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export function logRoutes(routingResponse: MultiRouteResponse) {
const routes = routingResponse.results
if (routes.length > 0) {
console.log(`- found ${routes.length} routes:`)
for (const route of routes) {
console.log(` - route: ${route.swaps.map(swap => swap.swapperId).join(' -> ')}`)
for (const [index, route] of routes.entries()) {
console.log(` - route ${index}: ${route.swaps.map(swap => swap.swapperId).join(' -> ')}`)
console.log(` - result type: ${route.resultType}`)
console.log(` - output: ${route.outputAmount} ${route.swaps[route.swaps.length - 1].to.symbol}`)
console.log(` - tags: ${route.tags.map(tag => tag.label).join(', ') || '-'}`)
Expand Down Expand Up @@ -72,9 +72,9 @@ export function logStepStatus(state: TransactionStatusResponse) {

export function logTransactionHash(hash: string, isApproval: boolean) {
if (isApproval) {
console.log(` - approve transaction hash: ${hash}`)
console.log(` - sending approve transaction: ${hash}`)
} else {
console.log(` - main transaction hash: ${hash}`)
console.log(` - sending main transaction: ${hash}`)
}
}

Expand Down

0 comments on commit ad9c044

Please sign in to comment.