Skip to content

Commit

Permalink
Deploy Token functionality. Code cleanup. (#5)
Browse files Browse the repository at this point in the history
* save work

* Simplify. Clean up mocks

* More test stuff

* save

* New mocks

* clean up files

* more cleanup

* More type fixes

* Fix tests

* Cleanup dead files

* Fix this

* Add ethereum

* Add some more tests

* Clean up packages

* Clean up types
  • Loading branch information
r-near authored Dec 14, 2024
1 parent 3b3ceb6 commit d50f321
Show file tree
Hide file tree
Showing 26 changed files with 538 additions and 598 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"license": "MIT",
"dependencies": {
"@solana/web3.js": "^1.95.5",
"borsh": "^2.0.0",
"borsher": "^3.5.0",
"ethers": "^6.13.4",
"near-api-js": "^5.0.1"
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

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

15 changes: 10 additions & 5 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// api.ts
import { type Chain, type Fee, type OmniAddress, Status } from "./types"
import { type ChainKind, type OmniAddress, Status } from "./types"

export interface ApiTransferResponse {
id: {
origin_chain: "Eth" | "Near" | "Sol" | "Arb" | "Base"
origin_chain: keyof ChainKind
origin_nonce: number
}
status: "Initialized" | "FinalisedOnNear" | "Finalised"
Expand All @@ -24,6 +24,11 @@ export interface ApiFeeResponse {
usd_fee: number
}

export type ApiFee = {
fee: bigint
nativeFee: bigint
}

export class OmniBridgeAPI {
private baseUrl: string

Expand All @@ -38,9 +43,9 @@ export class OmniBridgeAPI {
return this.baseUrl
}

async getTransferStatus(originChain: Chain, nonce: bigint): Promise<Status> {
async getTransferStatus(originChain: ChainKind, nonce: bigint): Promise<Status> {
const params = new URLSearchParams({
origin_chain: originChain,
origin_chain: Object.keys(originChain)[0].toLowerCase(),
origin_nonce: nonce.toString(),
})

Expand All @@ -62,7 +67,7 @@ export class OmniBridgeAPI {
}
}

async getFee(sender: OmniAddress, recipient: OmniAddress, tokenAddress: string): Promise<Fee> {
async getFee(sender: OmniAddress, recipient: OmniAddress, tokenAddress: string): Promise<ApiFee> {
const params = new URLSearchParams({
sender: sender,
recipient: recipient,
Expand Down
209 changes: 108 additions & 101 deletions src/chains/ethereum.ts
Original file line number Diff line number Diff line change
@@ -1,121 +1,128 @@
import { Contract, type Wallet } from "ethers"
import { Chain, type ChainDeployer, type OmniAddress, type TokenDeployment } from "../types"
import { ethers } from "ethers"
import { type ChainDeployer, ChainKind, type OmniAddress } from "../types"
import { getChain } from "../utils"

const FACTORY_ABI = [
"function logMetadata(address tokenAddress) external",
"function deployToken(bytes signatureData, tuple(string token, string name, string symbol, uint8 decimals) metadata) payable external returns (address)",
"event LogMetadata(address tokenAddress, string name, string symbol, uint8 decimals)",
"event DeployToken(address bridgeTokenProxy, string token, string name, string symbol, uint8 decimals)",
]

interface MetadataPayload {
token: string
name: string
symbol: string
decimals: number
}

export class EthereumDeployer implements ChainDeployer {
private factory: Contract

// Contract ABI for the bridge token factory
const BRIDGE_TOKEN_FACTORY_ABI = [
"function deployToken(bytes signatureData, tuple(string token, string name, string symbol, uint8 decimals) metadata) external returns (address)",
"function finTransfer(bytes signature, tuple(uint64 destinationNonce, uint8 originChain, uint64 originNonce, address tokenAddress, uint128 amount, address recipient, string feeRecipient) transferPayload) external",
"function initTransfer(address tokenAddress, uint128 amount, uint128 fee, uint128 nativeFee, string recipient, string message) external",
"function nearToEthToken(string nearTokenId) external view returns (address)",
] as const

const ERC20_ABI = [
"function allowance(address owner, address spender) public view returns (uint256)",
"function approve(address spender, uint256 amount) external returns (bool)",
] as const

/**
* Gas limits for Ethereum transactions
* @internal
*/
const GAS_LIMIT = {
DEPLOY_TOKEN: 500000,
APPROVE: 60000,
TRANSFER: 200000,
} as const

/**
* Ethereum blockchain implementation of the token deployer
* @implements {ChainDeployer<ethers.Signer>}
*/
export class EthereumDeployer implements ChainDeployer<ethers.Signer> {
private factory: ethers.Contract

/**
* Creates a new Ethereum token deployer instance
* @param wallet - Ethereum signer instance for transaction signing
* @param factoryAddress - Address of the bridge token factory contract
* @throws {Error} If factory address is not configured
*/
constructor(
private wallet: Wallet,
private network: "testnet" | "mainnet",
factoryAddress = process.env.OMNI_FACTORY_ETHEREUM,
private wallet: ethers.Signer,
private factoryAddress: string = process.env.OMNI_FACTORY_ETH as string,
) {
if (!factoryAddress) {
throw new Error("OMNI_FACTORY_ETHEREUM address not configured")
if (!this.factoryAddress) {
throw new Error("OMNI_FACTORY_ETH address not configured")
}
this.factory = new Contract(factoryAddress, FACTORY_ABI, wallet)
this.factory = new ethers.Contract(this.factoryAddress, BRIDGE_TOKEN_FACTORY_ABI, this.wallet)
}

async initDeployToken(
tokenAddress: OmniAddress,
destinationChain: Chain,
): Promise<TokenDeployment> {
async initDeployToken(tokenAddress: OmniAddress): Promise<string> {
// Validate source chain is Ethereum
if (getChain(tokenAddress) !== Chain.Ethereum) {
throw new Error("Token address must be on Ethereum chain")
if (getChain(tokenAddress) !== ChainKind.Eth) {
throw new Error("Token address must be on Ethereum")
}

// Extract token contract address from OmniAddress
const [_, tokenContractAddress] = tokenAddress.split(":")

try {
// Call logMetadata
const tx = await this.factory.logMetadata(tokenContractAddress)
const receipt = await tx.wait()

// Find LogMetadata event
const event = receipt.events?.find((e: { event: string }) => e.event === "LogMetadata")
if (!event) {
throw new Error("LogMetadata event not found in transaction receipt")
}

return {
id: tx.hash,
tokenAddress,
sourceChain: Chain.Ethereum,
destinationChain,
status: "pending",
}
} catch (error) {
throw new Error(`Failed to initialize token deployment: ${error}`)
}
// Extract token address from OmniAddress
const [_, tokenAccountId] = tokenAddress.split(":")

// Get token contract to fetch metadata
const tokenContract = new ethers.Contract(
tokenAccountId,
[
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
],
this.wallet,
)

const [name, symbol, decimals] = await Promise.all([
tokenContract.name(),
tokenContract.symbol(),
tokenContract.decimals(),
])

// Call deployToken with metadata
const tx = await this.factory.deployToken(
"0x", // signatureData - empty for init
{
token: tokenAccountId,
name,
symbol,
decimals,
},
{ gasLimit: GAS_LIMIT.DEPLOY_TOKEN },
)

return tx.hash
}

async finDeployToken(deployment: TokenDeployment): Promise<TokenDeployment> {
if (deployment.status !== "ready_for_finalize") {
throw new Error(`Invalid deployment status: ${deployment.status}`)
}

if (!deployment.proof) {
throw new Error("Deployment proof missing")
}
async finDeployToken(_destinationChain: ChainKind, vaa: string): Promise<string> {
const tx = await this.factory.deployToken(
vaa, // Signed VAA from the source chain
{
token: "", // These will be extracted from the VAA
name: "",
symbol: "",
decimals: 0,
},
{ gasLimit: GAS_LIMIT.DEPLOY_TOKEN },
)

return tx.hash
}

try {
// Extract proof components
const { signatureData, metadata } = JSON.parse(deployment.proof) as {
signatureData: string
metadata: MetadataPayload
}

// Call deployToken
const tx = await this.factory.deployToken(
signatureData,
metadata,
{ gasLimit: 2000000 }, // You might want to estimate this
)
const receipt = await tx.wait()

// Find DeployToken event
const event = receipt.events?.find((e: { event: string }) => e.event === "DeployToken")
if (!event) {
throw new Error("DeployToken event not found in transaction receipt")
}

return {
...deployment,
status: "finalized",
deploymentTx: tx.hash,
}
} catch (error) {
throw new Error(`Failed to finalize token deployment: ${error}`)
}
async bindToken(_destinationChain: ChainKind, _vaa: string): Promise<string> {
// For Ethereum, binding typically happens in the deployToken call
// This is included for interface compatibility
throw new Error("Token binding not required for Ethereum")
}

async bindToken(deployment: TokenDeployment): Promise<TokenDeployment> {
// For Ethereum, there's no bind step - token is immediately usable
// after deployment. We'll just validate and return.
/**
* Helper to check and set token approvals
* @internal
*/
private async ensureApproval(tokenAddress: string, amount: bigint): Promise<void> {
const token = new ethers.Contract(tokenAddress, ERC20_ABI, this.wallet)

if (deployment.status !== "ready_for_bind") {
throw new Error(`Invalid deployment status: ${deployment.status}`)
}
const address = await this.wallet.getAddress()
const allowance = await token.allowance(address, this.factoryAddress)

return {
...deployment,
status: "completed",
if (allowance < amount) {
const tx = await token.approve(this.factoryAddress, amount, { gasLimit: GAS_LIMIT.APPROVE })
await tx.wait()
}
}
}
Loading

0 comments on commit d50f321

Please sign in to comment.