Skip to content

Commit

Permalink
refactor: Add nearOnEthSyncHeight|ethOnNearSyncHeight, convert utils …
Browse files Browse the repository at this point in the history
…to .ts.
  • Loading branch information
paouvrard committed May 25, 2021
1 parent edbee11 commit f9a8264
Show file tree
Hide file tree
Showing 17 changed files with 82 additions and 46 deletions.
12 changes: 12 additions & 0 deletions .pnp.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
3 changes: 3 additions & 0 deletions packages/near-ether/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ A Connector Library for sending native NEAR and Ether(ETH) over the Rainbow Brid
This is a Connector Library that integrates with [@near-eth/client]. For detailed instructions on how to use it, see the README there.

This package makes it easy for your app (or, someday, CLI) to send NEAR and Ether(ETH) over the Rainbow Bridge, using the [Connector contracts](https://github.com/aurora-is-near/near-erc20-connector). It lets you send NEAR Tokens (NEAR's Native Token) over the Rainbow Bridge, where they become eNEAR [ERC20] Tokens (Ethereum's Fungible Token Standard), and can then be sent back again.

[@near-eth/client]: https://www.npmjs.com/package/@near-eth/client
[ERC20]: https://eips.ethereum.org/EIPS/eip-20
4 changes: 2 additions & 2 deletions packages/near-ether/src/bridged-near/sendToNear/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { utils } from 'near-api-js'
import { stepsFor } from '@near-eth/client/dist/i18nHelpers'
import * as status from '@near-eth/client/dist/statuses'
import { getEthProvider, getNearAccount, formatLargeNum } from '@near-eth/client/dist/utils'
import { urlParams, lastBlockNumber } from '@near-eth/utils'
import { urlParams, ethOnNearSyncHeight } from '@near-eth/utils'
import { findReplacementTx } from 'find-replacement-tx'
import findProof from './findProof'

Expand Down Expand Up @@ -327,7 +327,7 @@ async function checkBurn (transfer) {
async function checkSync (transfer) {
const burnReceipt = last(transfer.burnReceipts)
const eventEmittedAt = burnReceipt.blockNumber
const syncedTo = await lastBlockNumber()
const syncedTo = await ethOnNearSyncHeight()
const completedConfirmations = Math.max(0, syncedTo - eventEmittedAt)

if (completedConfirmations < transfer.neededConfirmations) {
Expand Down
13 changes: 4 additions & 9 deletions packages/near-ether/src/natural-near/sendToEthereum/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import * as status from '@near-eth/client/dist/statuses'
import { stepsFor } from '@near-eth/client/dist/i18nHelpers'
import { track } from '@near-eth/client'
import { borshifyOutcomeProof, urlParams } from '@near-eth/utils'
import { borshifyOutcomeProof, urlParams, nearOnEthSyncHeight } from '@near-eth/utils'
import { getEthProvider, getNearAccount, formatLargeNum } from '@near-eth/client/dist/utils'
import { findReplacementTx } from 'find-replacement-tx'
import findProof from './findProof'
Expand Down Expand Up @@ -521,7 +521,8 @@ async function checkFinality (transfer) {
* @param {*} transfer
*/
async function checkSync (transfer) {
const web3 = new Web3(getEthProvider())
const provider = getEthProvider()
const web3 = new Web3(provider)
const ethNetwork = await web3.eth.net.getNetworkType()
if (ethNetwork !== process.env.ethNetworkId) {
console.log(
Expand All @@ -531,14 +532,8 @@ async function checkSync (transfer) {
return transfer
}

const nearOnEthClient = new web3.eth.Contract(
JSON.parse(process.env.ethNearOnEthClientAbiText),
process.env.ethClientAddress
)

const lockReceiptBlockHeight = last(transfer.lockReceiptBlockHeights)
const { currentHeight } = await nearOnEthClient.methods.bridgeState().call()
const nearOnEthClientBlockHeight = Number(currentHeight)
const nearOnEthClientBlockHeight = await nearOnEthSyncHeight(provider)

if (nearOnEthClientBlockHeight <= lockReceiptBlockHeight) {
return {
Expand Down
13 changes: 4 additions & 9 deletions packages/nep141-erc20/src/bridged-nep141/sendToEthereum/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import * as status from '@near-eth/client/dist/statuses'
import { stepsFor } from '@near-eth/client/dist/i18nHelpers'
import { track } from '@near-eth/client'
import { borshifyOutcomeProof, urlParams } from '@near-eth/utils'
import { borshifyOutcomeProof, urlParams, nearOnEthSyncHeight } from '@near-eth/utils'
import { findReplacementTx } from 'find-replacement-tx'
import { getEthProvider, getNearAccount, formatLargeNum } from '@near-eth/client/dist/utils'
import getNep141Address from '../getAddress'
Expand Down Expand Up @@ -538,7 +538,8 @@ async function checkFinality (transfer) {
* @param {*} transfer
*/
async function checkSync (transfer) {
const web3 = new Web3(getEthProvider())
const provider = getEthProvider()
const web3 = new Web3(provider)
const ethNetwork = await web3.eth.net.getNetworkType()
if (ethNetwork !== process.env.ethNetworkId) {
console.log(
Expand All @@ -548,14 +549,8 @@ async function checkSync (transfer) {
return transfer
}

const nearOnEthClient = new web3.eth.Contract(
JSON.parse(process.env.ethNearOnEthClientAbiText),
process.env.ethClientAddress
)

const withdrawBlockHeight = last(transfer.withdrawReceiptBlockHeights)
const { currentHeight } = await nearOnEthClient.methods.bridgeState().call()
const nearOnEthClientBlockHeight = Number(currentHeight)
const nearOnEthClientBlockHeight = await nearOnEthSyncHeight(provider)

if (nearOnEthClientBlockHeight <= withdrawBlockHeight) {
return {
Expand Down
4 changes: 2 additions & 2 deletions packages/nep141-erc20/src/natural-erc20/sendToNear/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { utils } from 'near-api-js'
import { stepsFor } from '@near-eth/client/dist/i18nHelpers'
import * as status from '@near-eth/client/dist/statuses'
import { getEthProvider, getNearAccount, formatLargeNum } from '@near-eth/client/dist/utils'
import { urlParams, lastBlockNumber } from '@near-eth/utils'
import { urlParams, ethOnNearSyncHeight } from '@near-eth/utils'
import { findReplacementTx } from 'find-replacement-tx'
import getName from '../getName'
import getAllowance from '../getAllowance'
Expand Down Expand Up @@ -495,7 +495,7 @@ async function checkLock (transfer) {
async function checkSync (transfer) {
const lockReceipt = last(transfer.lockReceipts)
const eventEmittedAt = lockReceipt.blockNumber
const syncedTo = await lastBlockNumber()
const syncedTo = await ethOnNearSyncHeight()
const completedConfirmations = Math.max(0, syncedTo - eventEmittedAt)

if (completedConfirmations < transfer.neededConfirmations) {
Expand Down
3 changes: 2 additions & 1 deletion packages/utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ Usage
```js
import {
urlParams,
lastBlockNumber,
ethOnNearSyncHeight,
nearOnEthSyncHeight,
borshifyOutcomeProof
} from '@near-eth/utils'
```
2 changes: 2 additions & 0 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
"@commitlint/config-conventional": "*",
"@commitlint/travis-cli": "*",
"@types/bn.js": "^5.1.0",
"@types/bs58": "^4.0.1",
"@types/node": "^14.14.28",
"@yarnpkg/pnpify": "^2.4.0",
"typescript": "4.1.5"
},
"dependencies": {
"bs58": "^4.0.1",
"near-api-js": "^0.39.0",
"web3": "^1.3.4",
"web3-utils": "^1.3.4"
},
"browserslist": [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import utils from 'web3-utils'
const bs58 = require('bs58')
import bs58 from 'bs58'

// Encode outcome proof according to its borsh schema.
export function borshifyOutcomeProof (proof) {
const statusToBuffer = (status) => {
// import { LightClientProof } from 'near-api-js/lib/providers/provider'
// export function borshifyOutcomeProof (proof: LightClientProof): Buffer {
// TODO fix LightClientProof interface
export function borshifyOutcomeProof (proof: any): Buffer {
const statusToBuffer = (status: any): Buffer => {
if ('SuccessValue' in status) {
const data = Buffer.from(status.SuccessValue, 'base64')
return Buffer.concat([
Expand All @@ -23,7 +26,7 @@ export function borshifyOutcomeProof (proof) {
return Buffer.concat([
utils.toBN(proof.outcome_proof.proof.length).toBuffer('le', 4),
Buffer.concat(
proof.outcome_proof.proof.map((p) =>
proof.outcome_proof.proof.map((p: any) =>
Buffer.concat([
bs58.decode(p.hash),
Buffer.from([p.direction === 'Right' ? 1 : 0])
Expand All @@ -44,7 +47,7 @@ export function borshifyOutcomeProof (proof) {
.toBN(proof.outcome_proof.outcome.receipt_ids.length)
.toBuffer('le', 4),
Buffer.concat(
proof.outcome_proof.outcome.receipt_ids.map((r) => bs58.decode(r))
proof.outcome_proof.outcome.receipt_ids.map((r: any) => bs58.decode(r))
),

utils.toBN(proof.outcome_proof.outcome.gas_burnt).toBuffer('le', 8),
Expand Down Expand Up @@ -81,7 +84,7 @@ export function borshifyOutcomeProof (proof) {

utils.toBN(proof.block_proof.length).toBuffer('le', 4),
Buffer.concat(
proof.block_proof.map((bp) =>
proof.block_proof.map((bp: any) =>
Buffer.concat([
bs58.decode(bp.hash),
Buffer.from([bp.direction === 'Right' ? 1 : 0])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import {

const near = new Near({
keyStore: new keyStores.InMemoryKeyStore(),
networkId: process.env.nearNetworkId,
nodeUrl: process.env.nearNodeUrl
networkId: process.env.nearNetworkId!,
nodeUrl: process.env.nearNodeUrl!
})

// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class EthOnNearClientBorsh {
constructor (args) {
constructor (args: any) {
Object.assign(this, args)
}
}
Expand All @@ -24,17 +25,17 @@ const schema = new Map([
}]
])

function deserializeEthOnNearClient (raw) {
function deserializeEthOnNearClient (raw: Buffer): any {
return deserializeBorsh(schema, EthOnNearClientBorsh, raw)
}

export async function lastBlockNumber () {
export async function ethOnNearSyncHeight (): Promise<number> {
// near-api-js requires instantiating an "account" object, even though view
// functions require no signature and therefore no associated account, so the
// account name passed in doesn't matter.
const account = await near.account(process.env.nearClientAccount)
const account = await near.account(process.env.nearClientAccount!)
const deserialized = await account.viewFunction(
process.env.nearClientAccount,
process.env.nearClientAccount!,
'last_block_number',
{},
{ parse: deserializeEthOnNearClient }
Expand Down
3 changes: 0 additions & 3 deletions packages/utils/src/index.js

This file was deleted.

4 changes: 4 additions & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * as urlParams from './url-params'
export { borshifyOutcomeProof } from './borshify-proof'
export { ethOnNearSyncHeight } from './ethOnNearClient'
export { nearOnEthSyncHeight } from './nearOnEthClient'
11 changes: 11 additions & 0 deletions packages/utils/src/nearOnEthClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Web3 from 'web3'

export async function nearOnEthSyncHeight (provider: any): Promise<number> {
const web3 = new Web3(provider)
const nearOnEthClient = new web3.eth.Contract(
JSON.parse(process.env.ethNearOnEthClientAbiText!),
process.env.ethClientAddress
)
const { currentHeight } = await nearOnEthClient.methods.bridgeState().call()
return Number(currentHeight)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
// dependence on URL Params only needed as workaround until
// https://github.com/near/near-api-js/pull/467 is merged

export function get (...paramNames) {
export function get (...paramNames: string[]): string | null | { [x: string]: string } {
const params = new URLSearchParams(window.location.search)

if (paramNames.length === 0) {
return Object.fromEntries(params.entries())
}

if (paramNames.length === 1) {
return params.get(paramNames[0])
return params.get(paramNames[0]!)
}

return paramNames.reduce(
Expand All @@ -20,21 +20,23 @@ export function get (...paramNames) {
)
}

export function set (newParams) {
export function set (newParams: { [x: string]: string }): void {
const params = new URLSearchParams(window.location.search)
for (const param in newParams) {
params.set(param, newParams[param])
params.set(param, newParams[param]!)
}
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
window.history.replaceState({}, '', `${location.pathname}?${params}`)
}

export function clear (...paramNames) {
export function clear (...paramNames: any[]): void {
if (paramNames.length === 0) {
window.history.replaceState({}, '', location.pathname)
} else {
const params = new URLSearchParams(window.location.search)
paramNames.forEach(p => params.delete(p))
if (params.toString()) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
window.history.replaceState({}, '', `${location.pathname}?${params}`)
} else {
window.history.replaceState({}, '', location.pathname)
Expand Down
1 change: 0 additions & 1 deletion packages/utils/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"extends": "../../tsconfig.json",
"include": ["src/*"],
"compilerOptions": {
"allowJs": true, /* Allow javascript files to be compiled. */
"outDir": "./dist/"
}
}
13 changes: 12 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -539,11 +539,13 @@ __metadata:
"@commitlint/config-conventional": "*"
"@commitlint/travis-cli": "*"
"@types/bn.js": ^5.1.0
"@types/bs58": ^4.0.1
"@types/node": ^14.14.28
"@yarnpkg/pnpify": ^2.4.0
bs58: ^4.0.1
near-api-js: ^0.39.0
typescript: 4.1.5
web3: ^1.3.4
web3-utils: ^1.3.4
languageName: unknown
linkType: soft
Expand Down Expand Up @@ -625,6 +627,15 @@ __metadata:
languageName: node
linkType: hard

"@types/bs58@npm:^4.0.1":
version: 4.0.1
resolution: "@types/bs58@npm:4.0.1"
dependencies:
base-x: ^3.0.6
checksum: 0fc89f90f50c3b86aa633fbb12dad0a37a2b2aff5e6ec50995ebce9d88f768a950afbbc43c7e1a10943a0991374892924346218f3dd0d7dfad108e09bc564a2f
languageName: node
linkType: hard

"@types/cacheable-request@npm:^6.0.1":
version: 6.0.1
resolution: "@types/cacheable-request@npm:6.0.1"
Expand Down Expand Up @@ -1314,7 +1325,7 @@ __metadata:
languageName: node
linkType: hard

"base-x@npm:^3.0.2, base-x@npm:^3.0.8":
"base-x@npm:^3.0.2, base-x@npm:^3.0.6, base-x@npm:^3.0.8":
version: 3.0.8
resolution: "base-x@npm:3.0.8"
dependencies:
Expand Down

0 comments on commit f9a8264

Please sign in to comment.