Skip to content

Commit

Permalink
refactor: start on cleaning up of examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Richards committed May 28, 2024
1 parent a034734 commit 22e4dbf
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 199 deletions.
14 changes: 2 additions & 12 deletions examples/node/examples/bridge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as lifiDataTypes from '@lifi/data-types'
import type { RouteExtended, Execution } from '@lifi/sdk'
import {
executeRoute,
getRoutes,
Expand All @@ -14,6 +13,7 @@ import { privateKeyToAccount } from 'viem/accounts'
import { mainnet, arbitrum, optimism, polygon } from 'viem/chains'
import 'dotenv/config'
import { promptConfirm } from '../helpers/promptConfirm'
import { reportStepsExecutionToTerminal } from '../helpers/reportStepsExecutionToTerminal'

const { findDefaultToken } = (lifiDataTypes as any).default

Expand Down Expand Up @@ -83,17 +83,7 @@ async function run() {

// here we are using the update route hook to report the execution steps to the terminal
const executionOptions = {
updateRouteHook: (updatedRoute: RouteExtended) => {
const lastExecution = updatedRoute.steps.reduce(
(accum, step) => {
if (step.execution) {
return step.execution
}
},
undefined as undefined | Execution
)
console.info(lastExecution)
},
updateRouteHook: reportStepsExecutionToTerminal,
}
await executeRoute(route, executionOptions)

Expand Down
80 changes: 14 additions & 66 deletions examples/node/examples/klimaRetireExactCarbon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import {
EVM,
getContractCallsQuote,
getStatus,
getTokenAllowance,
setTokenAllowance,
} from '@lifi/sdk'
import type { Chain, Address, Hash } from 'viem'
import type { Chain, Address } from 'viem'
import {
parseAbi,
encodeFunctionData,
Expand All @@ -24,7 +22,8 @@ import { mainnet, arbitrum, optimism, polygon } from 'viem/chains'
import { privateKeyToAccount } from 'viem/accounts'
import 'dotenv/config'
import { promptConfirm } from '../helpers/promptConfirm'
import { AddressZero } from './constants'
import { checkTokenAllowance } from './utils/checkTokenAllowance'
import { transformTxRequestToSendTxParams } from './utils/transformTxRequestToSendTxParams'

const { findDefaultToken } = (lifiDataTypes as any).default

Expand All @@ -33,7 +32,6 @@ const run = async () => {

try {
console.info('>> Initialize LiFi SDK')

const privateKey = process.env.PRIVATE_KEY as Address

// NOTE: Here we are using the private key to get the account,
Expand Down Expand Up @@ -89,7 +87,6 @@ const run = async () => {
chain: polygon,
transport: http(),
})

const sourceAmountDefaultRetirement = (await publicClient.readContract({
address: KLIMA_ETHEREUM_CONTRACT_POL,
abi,
Expand All @@ -100,14 +97,10 @@ const run = async () => {
retireAmount, // uint256 retireAmount,
],
})) as bigint

const usdcAmount = parseUnits(
sourceAmountDefaultRetirement.toString(),
USDCe_POL.decimals
).toString()

console.log('>> usdcAmount', usdcAmount)

const retireTxData = encodeFunctionData({
abi,
functionName: 'retireExactCarbonDefault',
Expand Down Expand Up @@ -142,7 +135,6 @@ const run = async () => {
},
],
}

console.info(
'>> create ContractCallsQuoteRequest',
contractCallsQuoteRequest
Expand All @@ -151,74 +143,30 @@ const run = async () => {
const contactCallsQuoteResponse = await getContractCallsQuote(
contractCallsQuoteRequest
)

console.info('>> Quote received', contactCallsQuoteResponse)

if (!(await promptConfirm('Execute Quote?'))) {
return
}

if (contactCallsQuoteResponse.action.fromToken.address !== AddressZero) {
const approval = await getTokenAllowance(
contactCallsQuoteResponse.action.fromToken,
account.address,
contactCallsQuoteResponse.estimate.approvalAddress
)

// set approval if needed
if (
approval &&
approval < BigInt(contactCallsQuoteResponse.action.fromAmount)
) {
const txHash = await setTokenAllowance({
walletClient: client,
spenderAddress: contactCallsQuoteResponse.estimate.approvalAddress,
token: contactCallsQuoteResponse.action.fromToken,
amount: BigInt(contactCallsQuoteResponse.action.fromAmount),
})

if (txHash) {
const transactionReceipt = await client.waitForTransactionReceipt({
hash: txHash,
retryCount: 20,
retryDelay: ({ count }: { count: number; error: Error }) =>
Math.min(~~(1 << count) * 200, 3000),
})

console.info(
`>> Set Token Allowance - transaction complete: amount: ${contactCallsQuoteResponse.action.fromToken} txHash: ${transactionReceipt.transactionHash}.`
)
}
}
}
await checkTokenAllowance(contactCallsQuoteResponse, account, client)

const transactionRequest =
contactCallsQuoteResponse.transactionRequest || {}

console.info('>> Execute transaction', transactionRequest)

const hash = await client.sendTransaction({
to: transactionRequest.to as Address,
account: client.account!,
data: transactionRequest.data as Hash,
value: transactionRequest.value
? BigInt(transactionRequest.value)
: undefined,
gas: transactionRequest.gasLimit
? BigInt(transactionRequest.gasLimit as string)
: undefined,
gasPrice: transactionRequest.gasPrice
? BigInt(transactionRequest.gasPrice as string)
: undefined,
chain: null,
})
console.info(
'>> Execute transaction',
contactCallsQuoteResponse.transactionRequest
)

const hash = await client.sendTransaction(
transformTxRequestToSendTxParams(
client.account,
contactCallsQuoteResponse.transactionRequest
)
)
console.info('>> Transaction sent', hash)

const receipt = await client.waitForTransactionReceipt({
hash,
})

console.info('>> Transaction receipt', receipt)

// wait for execution
Expand Down
64 changes: 14 additions & 50 deletions examples/node/examples/multihop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import { privateKeyToAccount } from 'viem/accounts'
import { AddressZero } from './constants'
import 'dotenv/config'
import { promptConfirm } from '../helpers/promptConfirm'
import { checkTokenAllowance } from './utils/checkTokenAllowance'
import { transformTxRequestToSendTxParams } from './utils/transformTxRequestToSendTxParams'

const { findDefaultToken } = (lifiDataTypes as any).default

Expand Down Expand Up @@ -128,60 +130,22 @@ const run = async () => {
return
}

if (contactCallsQuoteResponse.action.fromToken.address !== AddressZero) {
const approval = await getTokenAllowance(
contactCallsQuoteResponse.action.fromToken,
account.address,
contactCallsQuoteResponse.estimate.approvalAddress
)

// set approval if needed
if (
approval &&
approval < BigInt(contactCallsQuoteResponse.action.fromAmount)
) {
const txHash = await setTokenAllowance({
walletClient: client,
spenderAddress: contactCallsQuoteResponse.estimate.approvalAddress,
token: contactCallsQuoteResponse.action.fromToken,
amount: BigInt(contactCallsQuoteResponse.action.fromAmount),
})

if (txHash) {
const transactionReceipt = await client.waitForTransactionReceipt({
hash: txHash,
retryCount: 20,
retryDelay: ({ count }: { count: number; error: Error }) =>
Math.min(~~(1 << count) * 200, 3000),
})

console.info(
`>> Set Token Allowance - transaction complete: amount: ${contactCallsQuoteResponse.action.fromToken} txHash: ${transactionReceipt.transactionHash}.`
)
}
}
}
await checkTokenAllowance(contactCallsQuoteResponse, account, client)

const transactionRequest =
contactCallsQuoteResponse.transactionRequest || {}

console.info('>> Execute transaction', transactionRequest)

const hash = await client.sendTransaction({
to: transactionRequest.to as Address,
account: client.account!,
value: transactionRequest.value
? BigInt(transactionRequest.value)
: undefined,
data: transactionRequest.data as Hash,
gas: transactionRequest.gasLimit
? BigInt(transactionRequest.gasLimit as string)
: undefined,
gasPrice: transactionRequest.gasPrice
? BigInt(transactionRequest.gasPrice as string)
: undefined,
chain: null,
})
console.info(
'>> Execute transaction',
contactCallsQuoteResponse.transactionRequest
)

const hash = await client.sendTransaction(
transformTxRequestToSendTxParams(
client.account,
contactCallsQuoteResponse.transactionRequest
)
)

console.info('>> Transaction sent', hash)

Expand Down
73 changes: 14 additions & 59 deletions examples/node/examples/polynomialDeposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import {
EVM,
getContractCallsQuote,
getStatus,
getTokenAllowance,
setTokenAllowance,
} from '@lifi/sdk'
import type { Address, Chain, Hash } from 'viem'
import type { Address, Chain } from 'viem'
import {
createWalletClient,
encodeFunctionData,
Expand All @@ -22,6 +20,8 @@ import { mainnet, arbitrum, optimism, polygon } from 'viem/chains'
import 'dotenv/config'
import { promptConfirm } from '../helpers/promptConfirm'
import { AddressZero } from './constants'
import { checkTokenAllowance } from './utils/checkTokenAllowance'
import { transformTxRequestToSendTxParams } from './utils/transformTxRequestToSendTxParams'

const run = async () => {
console.info('>> Starting Polynomial Demo: Deposit sETH on Optimism')
Expand Down Expand Up @@ -99,7 +99,6 @@ const run = async () => {
},
],
}

console.info(
'>> create contract calls quote request',
contractCallsQuoteRequest
Expand All @@ -108,74 +107,30 @@ const run = async () => {
const contactCallsQuoteResponse = await getContractCallsQuote(
contractCallsQuoteRequest
)

console.info('>> Contract Calls Quote', contactCallsQuoteResponse)

if (!(await promptConfirm('Execute Quote?'))) {
return
}

if (contactCallsQuoteResponse.action.fromToken.address !== AddressZero) {
const approval = await getTokenAllowance(
contactCallsQuoteResponse.action.fromToken,
account.address,
contactCallsQuoteResponse.estimate.approvalAddress
)

// set approval if needed
if (
approval &&
approval < BigInt(contactCallsQuoteResponse.action.fromAmount)
) {
const txHash = await setTokenAllowance({
walletClient: client,
spenderAddress: contactCallsQuoteResponse.estimate.approvalAddress,
token: contactCallsQuoteResponse.action.fromToken,
amount: BigInt(contactCallsQuoteResponse.action.fromAmount),
})

if (txHash) {
const transactionReceipt = await client.waitForTransactionReceipt({
hash: txHash,
retryCount: 20,
retryDelay: ({ count }: { count: number; error: Error }) =>
Math.min(~~(1 << count) * 200, 3000),
})

console.info(
`>> Set Token Allowance - transaction complete: amount: ${contactCallsQuoteResponse.action.fromToken} txHash: ${transactionReceipt.transactionHash}.`
)
}
}
}
await checkTokenAllowance(contactCallsQuoteResponse, account, client)

const transactionRequest =
contactCallsQuoteResponse.transactionRequest || {}

console.info('>> Execute transaction', transactionRequest)

const hash = await client.sendTransaction({
to: transactionRequest.to as Address,
account: client.account!,
value: transactionRequest.value
? BigInt(transactionRequest.value as string)
: undefined,
data: transactionRequest.data as Hash,
gas: transactionRequest.gasLimit
? BigInt(transactionRequest.gasLimit as string)
: undefined,
gasPrice: transactionRequest.gasPrice
? BigInt(transactionRequest.gasPrice as string)
: undefined,
chain: null,
})
console.info(
'>> Execute transaction',
contactCallsQuoteResponse.transactionRequest
)

const hash = await client.sendTransaction(
transformTxRequestToSendTxParams(
client.account,
contactCallsQuoteResponse.transactionRequest
)
)
console.info('>> Transaction sent', hash)

const receipt = await client.waitForTransactionReceipt({
hash,
})

console.info('>> Transaction receipt', receipt)

// wait for execution
Expand Down
Loading

0 comments on commit 22e4dbf

Please sign in to comment.