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

Feat/celer bridge #6

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from 13 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
21 changes: 13 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,23 @@
## Oracles Module
### Chainlink
Implementation of the following 4 Chainlink features using the [Hardhat](https://hardhat.org/) development environment:
- [Chainlink Data Feeds on Klaytn](/packages/oracles-starter-kit/README.md)
- [Chainlink VRF on Klaytn](/packages/oracles-starter-kit/README.md)
- [Chainlink Keepers on Klaytn](/packages/oracles-starter-kit/README.md)
- [Request & Receive data on Klaytn](/packages/oracles-starter-kit/README.md)
- [Chainlink Data Feeds on Klaytn](/packages/oracles-starter-kit/README.md#chainlink-price-feeds)
- [Chainlink VRF on Klaytn](/packages/oracles-starter-kit/README.md#chainlink-vrf-get-a-random-number)
- [Chainlink Keepers on Klaytn](/packages/oracles-starter-kit/README.md#chainlink-keepers)
- [Request & Receive data on Klaytn](/packages/oracles-starter-kit/README.md#chainlink-request--receive-data)

### Witnet
- [Witnet Data Feeds on Klaytn](/packages/oracles-starter-kit/README.md)
- [Witnet Randomness on Klaytn](/packages/oracles-starter-kit/README.md)
- [Witnet Data Feeds on Klaytn](/packages/oracles-starter-kit/README.md#witnet-price-feeds)
- [Witnet Randomness on Klaytn](/packages/oracles-starter-kit/README.md#witnet-randomness)

## Bridges Module
`In progress`

## Bridges Module
### Celer Bridge
Implementations:
- [Transfer](/packages/bridges-starter-kit/celer/README.md#transfer)
- [Refund](/packages/bridges-starter-kit/celer/README.md#refund)
- [Mint](/packages/bridges-starter-kit/celer/README.md#mint)
- [Burn](/packages/bridges-starter-kit/celer/README.md#burn)
<br/>

# Getting started
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
"oracle:help": "yarn workspace oracles-starter-kit hardhat --help",
"oracle:compile": "yarn workspace oracles-starter-kit compile",
"oracle:deploy": "yarn workspace oracles-starter-kit hardhat deploy",
"oracle:test": "yarn workspace oracles-starter-kit test"
"oracle:test": "yarn workspace oracles-starter-kit test",
"celer:test-transfer": "yarn workspace cbridge-starter-kit ts-node examples/transferFlow.ts",
"celer:test-refund": "yarn workspace cbridge-starter-kit ts-node examples/refundFlow.ts",
"celer:test-mint": "yarn workspace cbridge-starter-kit ts-node examples/mintCanonicalToken.ts",
"celer:test-burn": "yarn workspace cbridge-starter-kit ts-node examples/burnCanonicalToken.ts"
},
"workspaces": {
"packages": [
Expand Down
7 changes: 7 additions & 0 deletions packages/bridges-starter-kit/celer/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CBRIDGE_GATEWAY_URL=
KLAYTN_RPC=
WALLET_ADDRESS=
PRIVATE_KEY=
ORIGINAL_TOKEN_VAULT_V2_CONTRACT=
Sotatek-ThooLuu marked this conversation as resolved.
Show resolved Hide resolved
PEGGED_TOKEN_BRIDGE_CONTRACT
PEGGED_TOKEN_BRIDGE_V2_CONTRACT=
39 changes: 39 additions & 0 deletions packages/bridges-starter-kit/celer/APIs/Estimate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
EstimateAmtRequest,
EstimateWithdrawAmtRequest,
WithdrawInfo,
} from "../ts-proto/gateway/gateway_pb"

export const estimateAmt = (
srcChainId: number,
dstChainId: number,
tokenSymbol: string,
usrAddr: string,
slippageTolerance: number,
amt: string
): EstimateAmtRequest => {
const estimateRequest = new EstimateAmtRequest()
estimateRequest.setSrcChainId(srcChainId)
estimateRequest.setDstChainId(dstChainId)
estimateRequest.setTokenSymbol(tokenSymbol)
estimateRequest.setUsrAddr(usrAddr)
estimateRequest.setSlippageTolerance(slippageTolerance)
estimateRequest.setAmt(amt)

return estimateRequest
}

export const estimateWithdrawAmt = (
withdrawItem: WithdrawInfo[],
dstChainId: number,
tokenSymbol: string,
usrAddr: string
): EstimateWithdrawAmtRequest => {
const estimateRequest = new EstimateWithdrawAmtRequest()
estimateRequest.setSrcWithdrawsList(withdrawItem)
estimateRequest.setDstChainId(dstChainId)
estimateRequest.setTokenSymbol(tokenSymbol)
estimateRequest.setUsrAddr(usrAddr)

return estimateRequest
}
76 changes: 76 additions & 0 deletions packages/bridges-starter-kit/celer/APIs/GetData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import {
EstimateWithdrawAmt,
EstimateWithdrawAmtResponse,
GetTransferStatusRequest,
GetTransferStatusResponse,
WithdrawInfo,
} from "../ts-proto/gateway/gateway_pb"
import { WebClient } from "../ts-proto/gateway/GatewayServiceClientPb"
import { BigNumber } from "ethers"
import { estimateWithdrawAmt } from "./Estimate"
import axios from "axios"
import { ITransferConfigs } from "../constants/type"
import { safeParseUnits } from "celer-web-utils/lib/format"

export const getTransferConfigs = (rpc: string): Promise<ITransferConfigs> =>
axios
.get(`${rpc}/v2/getTransferConfigsForAll`)
.then(({ data }) => data)
.catch((err) => console.log(err))

export const getTransferStatus = async (
rpc: string,
transferId: string
): Promise<GetTransferStatusResponse.AsObject> => {
const client = new WebClient(rpc, null, null)
const statusRequest = new GetTransferStatusRequest()
statusRequest.setTransferId(transferId)
const transferStatus = await client.getTransferStatus(statusRequest, null)
console.log("Transfer Status:", transferStatus.toObject())

return transferStatus.toObject()
}

export const getWithdrawInfo = (
chainId: number,
amount: string,
slippageTolerance: number
): WithdrawInfo => {
const withdrawInfo = new WithdrawInfo()
withdrawInfo.setChainId(chainId)
withdrawInfo.setAmount(safeParseUnits(amount, 6).toString())
withdrawInfo.setSlippageTolerance(slippageTolerance)

return withdrawInfo
}

export const getEstimation = async (
rpc: string,
addr: string,
chainId: number,
tokenSymbol: string,
amount: string,
slippageTolerance: number
) => {
const client = new WebClient(rpc, null, null)

const withdrawInfo = getWithdrawInfo(chainId, amount, slippageTolerance)
const estimateRequest = estimateWithdrawAmt(Array(withdrawInfo), chainId, tokenSymbol, addr)

const res: EstimateWithdrawAmtResponse = await client.estimateWithdrawAmt(estimateRequest, null)
let estimateResult = ""
if (!res.getErr() && res.getReqAmtMap()) {
const resMap = res.getReqAmtMap()
resMap.forEach((entry: EstimateWithdrawAmt, key: number) => {
if (key === chainId) {
const totleFee =
(Number(entry.getBaseFee()) + Number(entry.getPercFee())).toString() || "0"
const eqValueTokenAmtBigNum = BigNumber.from(entry.getEqValueTokenAmt())
const feeBigNum = BigNumber.from(totleFee)
const targetReceiveAmounts = eqValueTokenAmtBigNum.sub(feeBigNum)
estimateResult = targetReceiveAmounts.toString()
}
})
}
return estimateResult
}
43 changes: 43 additions & 0 deletions packages/bridges-starter-kit/celer/APIs/PoolBasedTransfer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { ITransferObject } from "../constants/type"
import { EstimateAmtRequest } from "../ts-proto/gateway/gateway_pb"
import { WebClient } from "../ts-proto/gateway/GatewayServiceClientPb"

import { transactor } from "../helper"
import { BigNumber, Contract } from "ethers"

export const poolBasedTransfer = async (
bridge: Contract,
rpc: string,
addr: string,
estimateRequest: EstimateAmtRequest,
transferObject: ITransferObject
): Promise<void> => {
const client = new WebClient(rpc, null, null)
const estimateAmount = await client.estimateAmt(estimateRequest, null)

const { transferToken, toChain, value, nonce } = transferObject

try {
await transactor(
transferToken?.token?.symbol === 'KLAY'
? bridge.sendNative(
addr,
value,
BigNumber.from(toChain?.id),
BigNumber.from(nonce),
BigNumber.from(estimateAmount.getMaxSlippage() || 0),
{ value }
)
: bridge.send(
addr,
transferToken?.token?.address,
value,
BigNumber.from(toChain?.id),
BigNumber.from(nonce),
BigNumber.from(estimateAmount.getMaxSlippage() || 0)
)
)
} catch (err: any) {
console.log("PoolBasedTransfer.ts - error:", err.reason)
}
}
41 changes: 41 additions & 0 deletions packages/bridges-starter-kit/celer/APIs/RequestRefund.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { WebClient } from "../ts-proto/gateway/GatewayServiceClientPb"
import { WithdrawLiquidityRequest, WithdrawMethodType } from "../ts-proto/gateway/gateway_pb"
import { WithdrawReq, WithdrawType } from "../ts-proto/sgn/cbridge/v1/tx_pb"
import { getTransferStatus } from "./GetData"

export const requestRefund = async (rpc: string, transferId: string, estimated: string) => {
const client = new WebClient(rpc, null, null)

const timestamp = Math.floor(Date.now() / 1000)
const withdrawReqProto = new WithdrawReq()
withdrawReqProto.setXferId(transferId)
withdrawReqProto.setReqId(timestamp)
withdrawReqProto.setWithdrawType(WithdrawType.WITHDRAW_TYPE_REFUND_TRANSFER)

const req = new WithdrawLiquidityRequest()
req.setWithdrawReq(withdrawReqProto.serializeBinary())
req.setEstimatedReceivedAmt(estimated)
req.setMethodType(WithdrawMethodType.WD_METHOD_TYPE_ONE_RM)

const wres = await client.withdrawLiquidity(req, null)
let detailInter
if (!wres.getErr()) {
detailInter = setInterval(async () => {
const res = await getTransferStatus(rpc, transferId)
if (res?.status) {
const status = res.status
if (status === 8) {
console.log("status:", res.status)
clearInterval(detailInter)
}
} else if (res.status === 0) {
console.error("status: unknown")
clearInterval(detailInter)
} else {
clearInterval(detailInter)
}
}, 5000)
} else {
console.log(`Refund error`, wres.getErr()?.toObject())
}
}
4 changes: 4 additions & 0 deletions packages/bridges-starter-kit/celer/APIs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { estimateAmt, estimateWithdrawAmt } from "./Estimate"
export { getEstimation, getTransferConfigs, getTransferStatus, getWithdrawInfo } from "./GetData"
export { poolBasedTransfer } from "./PoolBasedTransfer"
export { requestRefund } from "./RequestRefund"
Loading