diff --git a/examples/evm-to-evm-fungible-transfer/.env.sample b/examples/evm-to-evm-fungible-transfer/.env.sample deleted file mode 100644 index 3ccffb3..0000000 --- a/examples/evm-to-evm-fungible-transfer/.env.sample +++ /dev/null @@ -1 +0,0 @@ -PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE" \ No newline at end of file diff --git a/examples/evm-to-evm-generic-mesage-passing/.env.sample b/examples/evm-to-evm-generic-mesage-passing/.env.sample deleted file mode 100644 index 3ccffb3..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/.env.sample +++ /dev/null @@ -1 +0,0 @@ -PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE" \ No newline at end of file diff --git a/examples/evm-to-evm-generic-mesage-passing/README.md b/examples/evm-to-evm-generic-mesage-passing/README.md deleted file mode 100644 index 2f2be5b..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/README.md +++ /dev/null @@ -1,61 +0,0 @@ -## Sygma SDK Generic Message Example - -This is an example script that demonstrates the functionality of the SDK using the Sygma ecosystem. The script showcases generic message passing (execution of a function on the destination chain) between two networks using the Sygma SDK. - -## Prerequisites - -Before running the script, ensure that you have the following: - -- Node.js installed on your machine -- [Yarn](https://yarnpkg.com/) (version 3.4.1 or higher) -- Access to an Ethereum provider - -## Getting started - -### 1. Clone the repository - -To get started, clone this repository to your local machine with: - -```bash -git clone git@github.com:sygmaprotocol/sygma-sdk.git -cd sygma-sdk/ -``` - -### 2. Install dependencies - -Install the project dependencies by running: - -```bash -yarn install -``` - -### 3. Build the sdk - -To start the example you need to build the sdk first with: - -```bash -yarn sdk:build -``` - -## Usage - -To call a function on a destination chain contract: - -```bash -yarn run transfer -``` - -The example will use `ethers` in conjuction with the sygma-sdk to -call a function on a smart contract on `Goerli` by calling the Deposit method on `Sepolia` and passing the details of the function to be called. - -Replace the placeholder values in the `.env` file with your own Ethereum wallet private key and provider URL. - -## Script Functionality - -This example script performs the following steps: -- initializes the SDK and establishes a connection to the Ethereum provider. -- retrieves the list of supported domains and resources from the SDK configuration. -- Searches for the Generic Message Passing resource from the list of supported resources registered. -- Searches for the Goerli and Sepolia domains in the list of supported domains based on their chain IDs. -- Constructs a transfer object that defines the details of the destination chain smart contract, function and call-data -- Builds the final transfer transaction and sends it using the Ethereum wallet. diff --git a/examples/evm-to-evm-generic-mesage-passing/package.json b/examples/evm-to-evm-generic-mesage-passing/package.json deleted file mode 100644 index 32059a6..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@buildwithsygma/sygma-sdk-evm-to-evm-generic-message-example", - "version": "0.1.0", - "description": "Sygma sdk examples", - "type": "module", - "sideEffects": false, - "repository": { - "type": "git", - "url": "https://github.com/sygmaprotocol/sygma-sdk" - }, - "keywords": [ - "sygma", - "sygmaprotocol", - "buildwithsygma", - "web3", - "bridge", - "ethereum" - ], - "scripts": { - "transfer": "ts-node src/transfer.ts" - }, - "author": "Sygmaprotocol Product Team", - "license": "LGPL-3.0-or-later", - "devDependencies": { - "dotenv": "16.3.1", - "eslint": "8", - "eslint-config-prettier": "8.3.0", - "eslint-plugin-only-warn": "1.0.3", - "eslint-plugin-prettier": "4.0.0", - "ts-node": "10.9.1", - "typescript": "5.0.4" - }, - "dependencies": { - "@buildwithsygma/sygma-sdk-core": "workspace:*", - "ethers": "5.6.2" - } -} diff --git a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/Storage.ts b/examples/evm-to-evm-generic-mesage-passing/src/Contracts/Storage.ts deleted file mode 100644 index 4b21e1b..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/Storage.ts +++ /dev/null @@ -1,126 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BigNumber, - BigNumberish, - BytesLike, - CallOverrides, - ContractTransaction, - Overrides, - PopulatedTransaction, - Signer, - utils, -} from "ethers"; -import type { FunctionFragment, Result } from "@ethersproject/abi"; -import type { Listener, Provider } from "@ethersproject/providers"; -import type { - TypedEventFilter, - TypedEvent, - TypedListener, - OnEvent, -} from "./common"; - -export interface StorageInterface extends utils.Interface { - functions: { - "retrieve(address)": FunctionFragment; - "store(address,uint256)": FunctionFragment; - }; - - getFunction(nameOrSignatureOrTopic: "retrieve" | "store"): FunctionFragment; - - encodeFunctionData(functionFragment: "retrieve", values: [string]): string; - encodeFunctionData( - functionFragment: "store", - values: [string, BigNumberish] - ): string; - - decodeFunctionResult(functionFragment: "retrieve", data: BytesLike): Result; - decodeFunctionResult(functionFragment: "store", data: BytesLike): Result; - - events: {}; -} - -export interface Storage extends BaseContract { - connect(signerOrProvider: Signer | Provider | string): this; - attach(addressOrName: string): this; - deployed(): Promise; - - interface: StorageInterface; - - queryFilter( - event: TypedEventFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>; - - listeners( - eventFilter?: TypedEventFilter - ): Array>; - listeners(eventName?: string): Array; - removeAllListeners( - eventFilter: TypedEventFilter - ): this; - removeAllListeners(eventName?: string): this; - off: OnEvent; - on: OnEvent; - once: OnEvent; - removeListener: OnEvent; - - functions: { - retrieve( - depositor: string, - overrides?: CallOverrides - ): Promise<[BigNumber]>; - - store( - depositor: string, - val: BigNumberish, - overrides?: Overrides & { from?: string } - ): Promise; - }; - - retrieve(depositor: string, overrides?: CallOverrides): Promise; - - store( - depositor: string, - val: BigNumberish, - overrides?: Overrides & { from?: string } - ): Promise; - - callStatic: { - retrieve(depositor: string, overrides?: CallOverrides): Promise; - - store( - depositor: string, - val: BigNumberish, - overrides?: CallOverrides - ): Promise; - }; - - filters: {}; - - estimateGas: { - retrieve(depositor: string, overrides?: CallOverrides): Promise; - - store( - depositor: string, - val: BigNumberish, - overrides?: Overrides & { from?: string } - ): Promise; - }; - - populateTransaction: { - retrieve( - depositor: string, - overrides?: CallOverrides - ): Promise; - - store( - depositor: string, - val: BigNumberish, - overrides?: Overrides & { from?: string } - ): Promise; - }; -} diff --git a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/common.ts b/examples/evm-to-evm-generic-mesage-passing/src/Contracts/common.ts deleted file mode 100644 index 2fc40c7..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/common.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { Listener } from "@ethersproject/providers"; -import type { Event, EventFilter } from "ethers"; - -export interface TypedEvent< - TArgsArray extends Array = any, - TArgsObject = any -> extends Event { - args: TArgsArray & TArgsObject; -} - -export interface TypedEventFilter<_TEvent extends TypedEvent> - extends EventFilter {} - -export interface TypedListener { - (...listenerArg: [...__TypechainArgsArray, TEvent]): void; -} - -type __TypechainArgsArray = T extends TypedEvent ? U : never; - -export interface OnEvent { - ( - eventFilter: TypedEventFilter, - listener: TypedListener - ): TRes; - (eventName: string, listener: Listener): TRes; -} - -export type MinEthersFactory = { - deploy(...a: ARGS[]): Promise; -}; - -export type GetContractTypeFromFactory = F extends MinEthersFactory< - infer C, - any -> - ? C - : never; - -export type GetARGsTypeFromFactory = F extends MinEthersFactory - ? Parameters - : never; diff --git a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/Storage__factory.ts b/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/Storage__factory.ts deleted file mode 100644 index 2d7dd48..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/Storage__factory.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import { Signer, utils, Contract, ContractFactory, Overrides } from "ethers"; -import type { Provider, TransactionRequest } from "@ethersproject/providers"; -import type { Storage, StorageInterface } from "../Storage"; - -const _abi = [ - { - inputs: [ - { - internalType: "address", - name: "depositor", - type: "address", - }, - ], - name: "retrieve", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "depositor", - type: "address", - }, - { - internalType: "uint256", - name: "val", - type: "uint256", - }, - ], - name: "store", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, -] as const; - -const _bytecode = - "0x608060405234801561001057600080fd5b5061027c806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80630a79309b1461003b578063a271ced21461006b575b600080fd5b61005560048036038101906100509190610179565b610087565b60405161006291906101bf565b60405180910390f35b61008560048036038101906100809190610206565b6100cf565b005b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b806000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006101468261011b565b9050919050565b6101568161013b565b811461016157600080fd5b50565b6000813590506101738161014d565b92915050565b60006020828403121561018f5761018e610116565b5b600061019d84828501610164565b91505092915050565b6000819050919050565b6101b9816101a6565b82525050565b60006020820190506101d460008301846101b0565b92915050565b6101e3816101a6565b81146101ee57600080fd5b50565b600081359050610200816101da565b92915050565b6000806040838503121561021d5761021c610116565b5b600061022b85828601610164565b925050602061023c858286016101f1565b915050925092905056fea26469706673582212200d84cfa07fcafcf5f317a116d3568fb3205cb9892889351bffd3e8213765d0d264736f6c63430008130033"; - -type StorageConstructorParams = - | [signer?: Signer] - | ConstructorParameters; - -const isSuperArgs = ( - xs: StorageConstructorParams -): xs is ConstructorParameters => xs.length > 1; - -export class Storage__factory extends ContractFactory { - constructor(...args: StorageConstructorParams) { - if (isSuperArgs(args)) { - super(...args); - } else { - super(_abi, _bytecode, args[0]); - } - } - - override deploy(overrides?: Overrides & { from?: string }): Promise { - return super.deploy(overrides || {}) as Promise; - } - override getDeployTransaction( - overrides?: Overrides & { from?: string } - ): TransactionRequest { - return super.getDeployTransaction(overrides || {}); - } - override attach(address: string): Storage { - return super.attach(address) as Storage; - } - override connect(signer: Signer): Storage__factory { - return super.connect(signer) as Storage__factory; - } - - static readonly bytecode = _bytecode; - static readonly abi = _abi; - static createInterface(): StorageInterface { - return new utils.Interface(_abi) as StorageInterface; - } - static connect( - address: string, - signerOrProvider: Signer | Provider - ): Storage { - return new Contract(address, _abi, signerOrProvider) as Storage; - } -} diff --git a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/index.ts b/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/index.ts deleted file mode 100644 index dd4f27a..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/factories/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export { Storage__factory } from "./Storage__factory"; diff --git a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/index.ts b/examples/evm-to-evm-generic-mesage-passing/src/Contracts/index.ts deleted file mode 100644 index 843ba29..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/Contracts/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export type { Storage } from "./Storage"; -export * as factories from "./factories"; -export { Storage__factory } from "./factories/Storage__factory"; diff --git a/examples/evm-to-evm-generic-mesage-passing/src/transfer.ts b/examples/evm-to-evm-generic-mesage-passing/src/transfer.ts deleted file mode 100644 index 99823a0..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/src/transfer.ts +++ /dev/null @@ -1,143 +0,0 @@ -import dotenv from "dotenv"; -import { - EVMGenericMessageTransfer, - Environment, - getTransferStatusData, -} from "@buildwithsygma/sygma-sdk-core"; -import { BigNumber, Wallet, providers, utils } from "ethers"; -import { Storage__factory } from "./Contracts"; - -dotenv.config(); - -const privateKey = process.env.PRIVATE_KEY; - -if (!privateKey) { - throw new Error("Missing environment variable: PRIVATE_KEY"); -} - -const getStatus = async ( - txHash: string -): Promise<{ status: string; explorerUrl: string } | void> => { - try { - const data = await getTransferStatusData(Environment.TESTNET, txHash); - - return data as { status: string; explorerUrl: string }; - } catch (e) { - console.log("error: ", e); - } -}; - -const DESTINATION_CHAIN_ID = 5; // Goerli -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000000500"; // Generic Message Handler -const EXECUTE_CONTRACT_ADDRESS = "0xdFA5621F95675D37248bAc9e536Aab4D86766663"; -const EXECUTE_FUNCTION_SIGNATURE = "0xa271ced2"; -const MAX_FEE = "3000000"; -const sourceProvider = new providers.JsonRpcProvider( - "https://gateway.tenderly.co/public/sepolia" -); -const destinationProvider = new providers.JsonRpcProvider( - "https://rpc.goerli.eth.gateway.fm/" -); -const storageContract = Storage__factory.connect( - EXECUTE_CONTRACT_ADDRESS, - destinationProvider -); -const wallet = new Wallet(privateKey ?? "", sourceProvider); - -const fetchAfterValue = async (): Promise => - await storageContract.retrieve(await wallet.getAddress()); - -const sleep = (ms: number): Promise => - new Promise((r) => setTimeout(r, ms)); - -const waitUntilBridged = async ( - valueBefore: BigNumber, - intervalDuration: number = 15000, - attempts: number = 8 -): Promise => { - let i = 0; - let contractValueAfter: BigNumber; - for (;;) { - await sleep(intervalDuration); - contractValueAfter = await fetchAfterValue(); - if (!contractValueAfter.eq(valueBefore)) { - console.log("Transaction successfully bridged."); - console.log( - `Value after update: ${new Date( - contractValueAfter.toNumber() - ).toString()}` - ); - break; - } - i++; - if (i > attempts) { - // transaction should have been bridged already - console.log("transaction is taking too much time to bridge!"); - break; - } - } -}; - -export async function genericMessage(): Promise { - const contractValueBefore = await storageContract.retrieve( - await wallet.getAddress() - ); - console.log( - `Value before update: ${new Date( - contractValueBefore.toNumber() - ).toString()}` - ); - const messageTransfer = new EVMGenericMessageTransfer(); - await messageTransfer.init(sourceProvider, Environment.TESTNET); - - const EXECUTION_DATA = utils.defaultAbiCoder.encode(["uint"], [Date.now()]); - - const transfer = messageTransfer.createGenericMessageTransfer( - await wallet.getAddress(), - DESTINATION_CHAIN_ID, - RESOURCE_ID, - EXECUTE_CONTRACT_ADDRESS, - EXECUTE_FUNCTION_SIGNATURE, - EXECUTION_DATA, - MAX_FEE - ); - - const fee = await messageTransfer.getFee(transfer); - const transferTx = await messageTransfer.buildTransferTransaction( - transfer, - fee - ); - - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: ", response.hash); - - console.log("Waiting for relayers to bridge transaction..."); - - await waitUntilBridged(contractValueBefore); - - let dataResponse: undefined | { status: string; explorerUrl: string }; - - const id = setInterval(() => { - getStatus(response.hash) - .then((data) => { - if (data) { - dataResponse = data; - console.log("Status of the transfer", data.status); - } - }) - .catch(() => { - console.log("Transfer still not indexed, retrying..."); - }); - - if (dataResponse && dataResponse.status === "executed") { - console.log("Transfer executed successfully"); - clearInterval(id); - process.exit(0); - } - }, 5000); -} - -genericMessage().finally(() => {}); diff --git a/examples/evm-to-evm-generic-mesage-passing/tsconfig.json b/examples/evm-to-evm-generic-mesage-passing/tsconfig.json deleted file mode 100644 index be09b38..0000000 --- a/examples/evm-to-evm-generic-mesage-passing/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "module": "ES2022", - "allowJs": true, - "declaration": true, - "sourceMap": true, - "declarationMap": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true, - "esModuleInterop": true, - "downlevelIteration": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - }, - "ts-node": { - "esm": true, - "experimentalSpecifierResolution": "node" - }, - "include": [ - "src" - ] -} \ No newline at end of file diff --git a/examples/evm-to-substrate-fungible-transfer/.env.sample b/examples/evm-to-substrate-fungible-transfer/.env.sample deleted file mode 100644 index 3ccffb3..0000000 --- a/examples/evm-to-substrate-fungible-transfer/.env.sample +++ /dev/null @@ -1 +0,0 @@ -PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE" \ No newline at end of file diff --git a/examples/evm-to-substrate-fungible-transfer/.gitignore b/examples/evm-to-substrate-fungible-transfer/.gitignore deleted file mode 100644 index 2eea525..0000000 --- a/examples/evm-to-substrate-fungible-transfer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.env \ No newline at end of file diff --git a/examples/evm-to-substrate-fungible-transfer/README.md b/examples/evm-to-substrate-fungible-transfer/README.md deleted file mode 100644 index 68a64d2..0000000 --- a/examples/evm-to-substrate-fungible-transfer/README.md +++ /dev/null @@ -1,84 +0,0 @@ -## Sygma SDK ERC20 Example - -This is an example script that demonstrates the functionality of the SDK using the Sygma ecosystem. The script showcases an ERC20 token transfer between two networks using the Sygma SDK. - -## Prerequisites - -Before running the script, ensure that you have the following: - -- Node.js installed on your machine -- [Yarn](https://yarnpkg.com/) (version 3.4.1 or higher) -- Access to an Ethereum provider - -## Getting started - -### 1. Clone the repository - -To get started, clone this repository to your local machine with: - -```bash -git clone git@github.com:sygmaprotocol/sygma-sdk.git -cd sygma-sdk/ -``` - -### 2. Install dependencies - -Install the project dependencies by running: - -```bash -yarn install -``` - -### 3. Build the sdk - -To start the example you need to build the sdk first with: - -```bash -yarn sdk:build -``` - -## Usage - -This example uses the `dotenv` module to manage private keys. To run the example, you will need to configure your environment variable to include your test development account's [exported private key](https://support.metamask.io/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key). A `.env.sample` is provided as a template. - -**DO NOT COMMIT PRIVATE KEYS WITH REAL FUNDS TO GITHUB. DOING SO COULD RESULT IN COMPLETE LOSS OF YOUR FUNDS.** - -Create a `.env` file in the evm-to-substrate example folder: - -```bash -cd examples/evm-to-substrate-fungible-transfer -touch .env -``` - -Replace between the quotation marks your exported private key: - -`PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE"` - -To send a ERC20 example transfer run: - -```bash -yarn run transfer -``` - -The example will use `ethers` in conjuction with the sygma-sdk to -create a transfer from `Goerli` to `Rococo-Phala` with a GPHA token. - -Replace the placeholder values in the script with your own Ethereum wallet private key and provider URL. - -## Script Functionality - -This example script performs the following steps: - -- initializes the SDK and establishes a connection to the Ethereum provider. -- retrieves the list of supported domains and resources from the SDK configuration. -- Searches for the ERC20 token resource with the specified symbol -- Searches for the Goerli and Rococo-Phala domains in the list of supported domains based on their chain IDs -- Constructs a transfer object that defines the details of the ERC20 token transfer -- Retrieves the fee required for the transfer from the SDK. -- Builds the necessary approval transactions for the transfer and sends them using the Ethereum wallet. The approval transactions are required to authorize the transfer of ERC20 tokens. -- Builds the final transfer transaction and sends it using the Ethereum wallet. - -## Faucet - -To get the test tokens needed for the transfer go to: `https://faucet-ui-stage.buildwithsygma.com/`. -Get the `GPHA` test token from the faucet. diff --git a/examples/evm-to-substrate-fungible-transfer/package.json b/examples/evm-to-substrate-fungible-transfer/package.json deleted file mode 100644 index 1fb72f0..0000000 --- a/examples/evm-to-substrate-fungible-transfer/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@buildwithsygma/sygma-sdk-evm-to-substrate-fungible-transfer-example", - "version": "0.1.0", - "description": "Sygma sdk example - EVM to Substrate Transfer", - "type": "module", - "sideEffects": false, - "repository": { - "type": "git", - "url": "https://github.com/sygmaprotocol/sygma-sdk" - }, - "keywords": [ - "sygma", - "sygmaprotocol", - "buildwithsygma", - "web3", - "bridge", - "ethereum" - ], - "scripts": { - "transfer": "ts-node src/transfer.ts" - }, - "author": "Sygmaprotocol Product Team", - "license": "LGPL-3.0-or-later", - "devDependencies": { - "dotenv": "^16.3.1", - "eslint": "8", - "eslint-config-prettier": "8.3.0", - "eslint-plugin-only-warn": "1.0.3", - "eslint-plugin-prettier": "4.0.0", - "ts-node": "10.9.1", - "typescript": "5.0.4" - }, - "dependencies": { - "@buildwithsygma/sygma-sdk-core": "workspace:*", - "ethers": "5.6.2" - } -} diff --git a/examples/evm-to-substrate-fungible-transfer/src/transfer.ts b/examples/evm-to-substrate-fungible-transfer/src/transfer.ts deleted file mode 100644 index 4a0a195..0000000 --- a/examples/evm-to-substrate-fungible-transfer/src/transfer.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { - EVMAssetTransfer, - Environment, - getTransferStatusData, -} from "@buildwithsygma/sygma-sdk-core"; -import { Wallet, providers } from "ethers"; -import dotenv from "dotenv"; - -dotenv.config(); - -const privateKey = process.env.PRIVATE_KEY; -if (!privateKey) { - throw new Error("Missing environment variable: PRIVATE_KEY"); -} - -const ROCOCO_PHALA_CHAIN_ID = 5231; -const DESTINATION_ADDRESS = "5CDQJk6kxvBcjauhrogUc9B8vhbdXhRscp1tGEUmniryF1Vt"; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000001000"; - -const getStatus = async ( - txHash: string -): Promise<{ status: string; explorerUrl: string } | void> => { - try { - const data = await getTransferStatusData(Environment.TESTNET, txHash); - - return data as { status: string; explorerUrl: string }; - } catch (e) { - console.log("error: ", e); - } -}; - -export async function erc20Transfer(): Promise { - const provider = new providers.JsonRpcProvider( - "https://rpc.goerli.eth.gateway.fm/" - ); - const wallet = new Wallet(privateKey ?? "", provider); - const assetTransfer = new EVMAssetTransfer(); - await assetTransfer.init(provider, Environment.TESTNET); - - const transfer = await assetTransfer.createFungibleTransfer( - await wallet.getAddress(), - ROCOCO_PHALA_CHAIN_ID, - DESTINATION_ADDRESS, - RESOURCE_ID, - "500000000000000000" // 18 decimal places - // optional parachainID (e.g. KusamaParachain.SHIDEN) - ); - - const fee = await assetTransfer.getFee(transfer); - const approvals = await assetTransfer.buildApprovals(transfer, fee); - for (const approval of approvals) { - const response = await wallet.sendTransaction( - approval as providers.TransactionRequest - ); - console.log("Sent approval with hash: ", response.hash); - } - const transferTx = await assetTransfer.buildTransferTransaction( - transfer, - fee - ); - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: ", response.hash); - - let dataResponse: undefined | { status: string; explorerUrl: string }; - - const id = setInterval(() => { - getStatus(response.hash) - .then((data) => { - if (data) { - dataResponse = data; - console.log(data); - } - }) - .catch(() => { - console.log("Transfer still not indexed, retrying..."); - }); - - if (dataResponse && dataResponse.status === "executed") { - console.log("Transfer executed successfully"); - clearInterval(id); - process.exit(0); - } - }, 5000); -} - -erc20Transfer().finally(() => {}); diff --git a/examples/evm-to-substrate-fungible-transfer/tsconfig.json b/examples/evm-to-substrate-fungible-transfer/tsconfig.json deleted file mode 100644 index be09b38..0000000 --- a/examples/evm-to-substrate-fungible-transfer/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "module": "ES2022", - "allowJs": true, - "declaration": true, - "sourceMap": true, - "declarationMap": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true, - "esModuleInterop": true, - "downlevelIteration": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - }, - "ts-node": { - "esm": true, - "experimentalSpecifierResolution": "node" - }, - "include": [ - "src" - ] -} \ No newline at end of file diff --git a/examples/friendly-evm-to-evm-fungible-transfer/.env.sample b/examples/friendly-evm-to-evm-fungible-transfer/.env.sample new file mode 100644 index 0000000..1efd177 --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/.env.sample @@ -0,0 +1 @@ +PRIVATE_KEY="169d9b1c95b87ed2b3d7845e7d1a6cffe7d2825765c269b06621c3755a798653" \ No newline at end of file diff --git a/examples/evm-to-evm-fungible-transfer/.gitignore b/examples/friendly-evm-to-evm-fungible-transfer/.gitignore similarity index 100% rename from examples/evm-to-evm-fungible-transfer/.gitignore rename to examples/friendly-evm-to-evm-fungible-transfer/.gitignore diff --git a/examples/evm-to-evm-fungible-transfer/README.md b/examples/friendly-evm-to-evm-fungible-transfer/README.md similarity index 100% rename from examples/evm-to-evm-fungible-transfer/README.md rename to examples/friendly-evm-to-evm-fungible-transfer/README.md diff --git a/examples/evm-to-evm-fungible-transfer/package.json b/examples/friendly-evm-to-evm-fungible-transfer/package.json similarity index 90% rename from examples/evm-to-evm-fungible-transfer/package.json rename to examples/friendly-evm-to-evm-fungible-transfer/package.json index 16a9bf3..3073904 100644 --- a/examples/evm-to-evm-fungible-transfer/package.json +++ b/examples/friendly-evm-to-evm-fungible-transfer/package.json @@ -17,7 +17,8 @@ "ethereum" ], "scripts": { - "transfer": "ts-node src/transfer.ts" + "transfer": "ts-node src/transfer.ts", + "governance": "ts-node src/governance.ts" }, "author": "Sygmaprotocol Product Team", "license": "LGPL-3.0-or-later", diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/governance.ts b/examples/friendly-evm-to-evm-fungible-transfer/src/governance.ts new file mode 100644 index 0000000..f192a2e --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/src/governance.ts @@ -0,0 +1,127 @@ +// Import necessary modules from the Sygma SDK and ethers library +// import { +// EVMAssetTransfer, +// Environment, +// getTransferStatusData, +// } from "@buildwithsygma/sygma-sdk-core"; +// import { Wallet, providers } from "ethers"; +// import dotenv from "dotenv"; + +// Load environment variables from the .env file +// dotenv.config(); + +// Retrieve private key from environment variables +// const privateKey = process.env.PRIVATE_KEY; + +// Throw an error if private key is missing +// if (!privateKey) { +// throw new Error("Missing environment variable: PRIVATE_KEY"); +// } + +// Define chain IDs and resource ID +// const SEPOLIA_CHAIN_ID = 11155111; +// const GOERLI_CHAIN_ID = 5; // Replace with the actual Goerli chain ID +// const RESOURCE_ID = +// "0x0000000000000000000000000000000000000000000000000000000000000300"; + +// Define a function to get the status of a transaction +// const getStatus = async ( +// txHash: string +// ): Promise<{ status: string; explorerUrl: string } | void> => { +// try { +// // Get transfer status data from the Sygma SDK +// const data = await getTransferStatusData(Environment.TESTNET, txHash); + +// // Return the status data +// return data as { status: string; explorerUrl: string }; +// } catch (e) { +// // Log an error if there is an exception +// console.log("error:", e); +// } +// }; + +// Define the main cross-chain governance transfer function +// export async function crossChainGovernanceTransfer(): Promise { +// // Create JSON RPC providers for Goerli and Sepolia chains +// const goerliProvider = new providers.JsonRpcProvider( +// "https://rpc.goerli.eth.gateway.fm/" +// ); +// const sepoliaProvider = new providers.JsonRpcProvider( +// "https://rpc.sepolia.eth.gateway.fm/" // Replace with the actual Sepolia RPC URL +// ); + +// // Create a wallet using the private key and the Goerli provider +// const wallet = new Wallet(privateKey ?? "", goerliProvider); + +// // Create an instance of EVMAssetTransfer from the Sygma SDK +// const assetTransfer = new EVMAssetTransfer(); + +// // Initialize the asset transfer instance with the Sepolia provider and the TESTNET environment +// // @ts-ignore-next-line +// await assetTransfer.init(sepoliaProvider, Environment.TESTNET); + +// // Check if JSON RPC providers are available +// if (!goerliProvider || !sepoliaProvider) { +// // Log an error message and return if providers are not available +// console.error("Error: JSON RPC provider not available."); +// return; +// } + +// // Create a fungible transfer from Goerli to Sepolia +// const transfer = await assetTransfer.createFungibleTransfer( +// await wallet.getAddress(), +// SEPOLIA_CHAIN_ID, +// await wallet.getAddress(), // Sending to the same address on a different chain +// RESOURCE_ID, +// "5000000000000000000" // 18 decimal places +// ); + +// // Get the fee for the transfer +// const fee = await assetTransfer.getFee(transfer); + +// // Build and send approvals for the transfer +// const approvals = await assetTransfer.buildApprovals(transfer, fee); +// for (const approval of approvals) { +// const response = await wallet.sendTransaction( +// approval as providers.TransactionRequest +// ); +// console.log("Sent approval with hash: ", response.hash); +// } + +// // Build and send the transfer transaction +// const transferTx = await assetTransfer.buildTransferTransaction( +// transfer, +// fee +// ); +// const response = await wallet.sendTransaction( +// transferTx as providers.TransactionRequest +// ); + +// // Log the transfer hash +// console.log("Sent transfer with hash: ", response.hash); + +// // Initialize a variable to store transfer status data +// let dataResponse: undefined | { status: string; explorerUrl: string }; + +// // Set up an interval to check the status of the transfer +// const id = setInterval(async () => { +// // Get the status data for the transfer +// const statusData = await getStatus(response.hash); + +// // Update the dataResponse variable +// if (statusData) { +// dataResponse = statusData; +// console.log("Status of the transfer", dataResponse.status); +// } + +// // Check if the transfer is executed +// if (dataResponse && dataResponse.status === "executed") { +// console.log("Transfer executed successfully"); +// clearInterval(id); // Clear the interval +// process.exit(0); // Exit the process +// } +// }, 5000); // Check status every 5 seconds +// } + +// Execute the cross-chain governance transfer function +// crossChainGovernanceTransfer().finally(() => {}); diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/globals.css b/examples/friendly-evm-to-evm-fungible-transfer/src/public/globals.css new file mode 100644 index 0000000..7c72f34 --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/src/public/globals.css @@ -0,0 +1,19 @@ +@import url("https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"); +@import url("https://fonts.googleapis.com/css?family=Cabin:700"); +* { + -webkit-font-smoothing: antialiased; + box-sizing: border-box; +} +html, +body { + margin: 0px; + height: 100%; +} +/* a blue color as a generic focus style */ +button:focus-visible { + outline: 2px solid #4a90e2 !important; + outline: -webkit-focus-ring-color auto 5px !important; +} +a { + text-decoration: none; +} diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/div-card-card-1ee8r.png b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/div-card-card-1ee8r.png new file mode 100644 index 0000000..5a68136 Binary files /dev/null and b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/div-card-card-1ee8r.png differ diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame-1.png b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame-1.png new file mode 100644 index 0000000..1d7a76b Binary files /dev/null and b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame-1.png differ diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame.png b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame.png new file mode 100644 index 0000000..111472a Binary files /dev/null and b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/frame.png differ diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/group-4.png b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/group-4.png new file mode 100644 index 0000000..41f56fb Binary files /dev/null and b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/group-4.png differ diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/image-66.png b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/image-66.png new file mode 100644 index 0000000..44769dc Binary files /dev/null and b/examples/friendly-evm-to-evm-fungible-transfer/src/public/img/image-66.png differ diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/index.html b/examples/friendly-evm-to-evm-fungible-transfer/src/public/index.html new file mode 100644 index 0000000..4543fce --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/src/public/index.html @@ -0,0 +1,47 @@ + + + + + + + + +
+
+
+ + + + + +
+ +
+
+ + + + + + +
+
+ + + + diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/public/style.css b/examples/friendly-evm-to-evm-fungible-transfer/src/public/style.css new file mode 100644 index 0000000..62c737f --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/src/public/style.css @@ -0,0 +1,98 @@ +.desktop { + background-color: #ffffff; + display: flex; + flex-direction: row; + justify-content: center; + width: 100%; +} + +.desktop .div { + background-color: #ffffff; + width: 1440px; + height: 1393px; + position: relative; +} + +.desktop .overlap { + position: absolute; + width: 1440px; + height: 1010px; + top: 0; + left: 0; +} + +.desktop .image { + position: absolute; + width: 1440px; + height: 1007px; + top: 3px; + left: 0; + object-fit: cover; +} + +.desktop .group { + position: absolute; + width: 710px; + height: 203px; + top: 141px; + left: 372px; +} + +.desktop .frame { + position: absolute; + width: 1439px; + height: 108px; + top: 0; + left: 0; +} + +.desktop .overlap-group-wrapper { + position: absolute; + width: 120px; + height: 32px; + top: 491px; + left: 660px; + border-radius: 50px; +} + +.desktop .overlap-group { + position: relative; + width: 291px; + height: 60px; + top: -17px; + left: -86px; + background-color: #ef794b; + border-radius: 30px; +} + +.desktop .text-wrapper { + position: absolute; + width: 267px; + height: 21px; + top: 18px; + left: 12px; + font-family: "Cabin", Helvetica; + font-weight: 700; + color: #ffffff; + font-size: 40px; + text-align: center; + letter-spacing: 0; + line-height: 20px; + white-space: nowrap; +} + +.desktop .img { + position: absolute; + width: 1389px; + height: 108px; + top: 1285px; + left: 26px; +} + +.desktop .div-card-card { + position: absolute; + width: 1342px; + height: 146px; + top: 1010px; + left: 49px; +} diff --git a/examples/friendly-evm-to-evm-fungible-transfer/src/server.js b/examples/friendly-evm-to-evm-fungible-transfer/src/server.js new file mode 100644 index 0000000..9c2683d --- /dev/null +++ b/examples/friendly-evm-to-evm-fungible-transfer/src/server.js @@ -0,0 +1,29 @@ +import express from 'express'; +import { fileURLToPath } from 'url'; +import { dirname } from 'path'; + +const app = express(); +const port = process.env.PORT || 3000; + +// Get the directory path of the current module +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +// Serve static files from the public directory +app.use(express.static('public')); + +// Serve your HTML file +app.get('/', (req, res) => { + res.sendFile(__dirname + '/public/index.html'); +}); + +// Define a route for /transfer-assets +app.get('/transfer', (req, res) => { + // Add your transfer logic here + res.send('Transfer assets logic goes here!'); +}); + +// Start the server +app.listen(port, () => { + console.log(`Server is running on http://localhost:${port}`); +}); diff --git a/examples/evm-to-evm-fungible-transfer/src/transfer.ts b/examples/friendly-evm-to-evm-fungible-transfer/src/transfer.ts similarity index 100% rename from examples/evm-to-evm-fungible-transfer/src/transfer.ts rename to examples/friendly-evm-to-evm-fungible-transfer/src/transfer.ts diff --git a/examples/evm-to-evm-fungible-transfer/tsconfig.json b/examples/friendly-evm-to-evm-fungible-transfer/tsconfig.json similarity index 100% rename from examples/evm-to-evm-fungible-transfer/tsconfig.json rename to examples/friendly-evm-to-evm-fungible-transfer/tsconfig.json diff --git a/examples/local-fungible-transfer/README.md b/examples/local-fungible-transfer/README.md deleted file mode 100644 index 6bb0818..0000000 --- a/examples/local-fungible-transfer/README.md +++ /dev/null @@ -1,81 +0,0 @@ -## Sygma SDK Local Example - -This is an example script that demonstrates the functionality of the SDK using the Sygma ecosystem. -The script showcases fungible token transfer between two networks using the Sygma SDK. - -This example is prepared to work with [Sygma local setup](https://docs.buildwithsygma.com/sdk/advanced/localsetup) that can be found inside [relayer repository](https://github.com/sygmaprotocol/sygma-relayer). - -## Prerequisites - -Before running the script, ensure that you have the following: - -- Node.js installed on your machine -- [Yarn](https://yarnpkg.com/) (version 3.4.1 or higher) - -## Getting started - -### 1. Run local setup: - -#### Clone relayers repository - -First, clone the Sygma relayer repository to your local machine with: - -``` -git clone https://github.com/sygmaprotocol/sygma-relayer.git -``` - -#### Start local setup - -This will start the dockerized setup: - -``` -make example -``` - -### 2. Clone the repository - -Clone this repository to your local machine with: - -```bash -git clone git@github.com:sygmaprotocol/sygma-sdk.git -cd sygma-sdk/ -``` - -### 3. Install dependencies - -Install the project dependencies by running: - -```bash -yarn install -``` - -### 4. Build the sdk - -To start the example you need to build the sdk first with: - -```bash -yarn sdk:build -``` - -## 5. Usage - -To send a ERC20 example transfer run: - -```bash -yarn run transfer:evm-substrate -``` - -This example will use `ethers` in conjuction with the sygma-sdk to -create a transfer from `EVM1` to `Substrate` network. - -You can also run: - -```bash -yarn run transfer:substrate-evm -``` - -Similarly, this example will use `@polkadot/api` in conjuction with the sygma-sdk to -create a transfer from `Substrate` to `EVM1` network. - - -For more details check out documentation on [Sygma local setup](https://docs.buildwithsygma.com/sdk/advanced/localsetup). diff --git a/examples/local-fungible-transfer/package.json b/examples/local-fungible-transfer/package.json deleted file mode 100644 index f882125..0000000 --- a/examples/local-fungible-transfer/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@buildwithsygma/sygma-sdk-local-fungible-transfer-example", - "version": "0.1.0", - "description": "Sygma sdk example - Fungible asset transfer on local setup", - "type": "module", - "sideEffects": false, - "repository": { - "type": "git", - "url": "https://github.com/sygmaprotocol/sygma-sdk" - }, - "keywords": [ - "sygma", - "sygmaprotocol", - "buildwithsygma", - "web3", - "bridge", - "ethereum" - ], - "scripts": { - "transfer:evm-substrate": "ts-node src/transfer.ts 1", - "transfer:substrate-evm": "ts-node src/transfer.ts 2" - }, - "author": "Sygmaprotocol Product Team", - "license": "LGPL-3.0-or-later", - "devDependencies": { - "eslint": "8", - "eslint-config-prettier": "8.3.0", - "eslint-plugin-only-warn": "1.0.3", - "eslint-plugin-prettier": "4.0.0", - "ts-node": "10.9.1", - "typescript": "5.0.4" - }, - "dependencies": { - "@buildwithsygma/sygma-contracts": "2.4.1", - "@buildwithsygma/sygma-sdk-core": "workspace:*", - "@ethersproject/experimental": "^5.7.0", - "ethers": "5.6.2" - } -} diff --git a/examples/local-fungible-transfer/src/transfer.ts b/examples/local-fungible-transfer/src/transfer.ts deleted file mode 100644 index 38a8556..0000000 --- a/examples/local-fungible-transfer/src/transfer.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { - EVMAssetTransfer, - Environment, - Fungible, - Transfer, - SubstrateAssetTransfer, - SubstrateParachain, - SubstrateResource, -} from "@buildwithsygma/sygma-sdk-core"; -import { Wallet, providers, ethers, BigNumber } from "ethers"; -import { Keyring } from "@polkadot/keyring"; -import { cryptoWaitReady } from "@polkadot/util-crypto"; -import { ApiPromise, WsProvider } from "@polkadot/api"; -import { ERC20PresetMinterPauser__factory } from "@buildwithsygma/sygma-contracts"; -import { NonceManager } from "@ethersproject/experimental"; - -const ERC20_TOKEN_SYMBOL = "ERC20LRTest"; -const SUBSTRATE_DESTINATION_ADDRESS = - "5CDQJk6kxvBcjauhrogUc9B8vhbdXhRscp1tGEUmniryF1Vt"; -const EVM_DESTINATION_ADDRESS = "0xD31E89feccCf6f2DE10EaC92ADffF48D802b695C"; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000000300"; -const ERC20_TOKEN_ADDRESS = "0x78E5b9cEC9aEA29071f070C8cC561F692B3511A6"; - -// Local setup chain IDs -const EVM1_CHAIN_ID = 1337; -const EVM2_CHAIN_ID = 1338; -const SUBSTRATE_CHAIN_ID = 5; - -// Local setup RPC URLs -const EVM1_RPC_URL = "http://127.0.0.1:8545"; -const EVM2_RPC_URL = "http://127.0.0.1:8547"; -const SUBSTRATE_RPC_URL = "ws://127.0.0.1:9944"; - -const ALICE_MNEMONIC = - "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice"; -const wsProvider = new WsProvider(SUBSTRATE_RPC_URL); - -const provider = new providers.JsonRpcProvider(EVM1_RPC_URL); -const w = new Wallet( - "cc2c32b154490f09f70c1c8d4b997238448d649e0777495863db231c4ced3616", - provider -); -const wallet = new NonceManager(w); - -export async function fungibleTransferFromEVM(): Promise { - const keyring = new Keyring({ type: "sr25519" }); - await cryptoWaitReady(); - const account = keyring.addFromUri(ALICE_MNEMONIC); - - const assetTransfer = new EVMAssetTransfer(); - await assetTransfer.init(provider, Environment.LOCAL); - - const sender = await wallet.getAddress(); - const api = await ApiPromise.create({ provider: wsProvider }); - - const b = ( - await api.query.assets.account(2000, account.address) - ).toHuman() as { balance: string }; - const destinationBalanceBefore = BigNumber.from( - b.balance.split(",").join("") - ).toString(); - - const sourceErc20LR18Contract = ERC20PresetMinterPauser__factory.connect( - ERC20_TOKEN_ADDRESS, - wallet - ); - - const balanceBefore = ( - await sourceErc20LR18Contract.balanceOf(sender) - ).toString(); - - console.log(`Transferring 5 tokens from evm1 to substrate.`); - console.log(`Sender: ${sender}`); - console.log(`Sender token balance on evm1 network before:${balanceBefore}`); - console.log( - `Sender token balance on substrate network before:${destinationBalanceBefore}` - ); - - const transfer = await assetTransfer.createFungibleTransfer( - sender, - SUBSTRATE_CHAIN_ID, - account.address, - RESOURCE_ID, - "5000000000000000000" // 18 decimal places - ); - - const fee = await assetTransfer.getFee(transfer); - const approvals = await assetTransfer.buildApprovals(transfer, fee); - for (const approval of approvals) { - const response = await wallet.sendTransaction( - approval as providers.TransactionRequest - ); - console.log("Sent approval with hash: " + response.hash); - } - const transferTx = await assetTransfer.buildTransferTransaction( - transfer, - fee - ); - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: " + response.hash); - - console.log("Waiting for relayers to bridge transaction..."); - - let i = 0; - let destinationBalanceAfter: BigNumber; - for (; ;) { - await sleep(7000); - const d = ( - await api.query.assets.account(2000, account.address) - ).toHuman() as { balance: string }; - destinationBalanceAfter = BigNumber.from(d.balance.split(",").join("")); - if (!destinationBalanceAfter.eq(destinationBalanceBefore)) { - console.log("Transaction successfully bridged."); - break; - } - i++; - if (i > 5) { - // transaction should have been bridged already - console.log("transaction is taking too much time to bridge!"); - break; - } - } - - const balanceAfter = ( - await sourceErc20LR18Contract.balanceOf(sender) - ).toString(); - - console.log(`Sender token balance on evm1 network after: ${balanceAfter}`); - console.log( - `Sender token balance on substrate network after: ${destinationBalanceAfter.toString()}` - ); -} - -export async function fungibleTransferFromSubstrate(): Promise { - const keyring = new Keyring({ type: "sr25519" }); - await cryptoWaitReady(); - const account = keyring.addFromUri(ALICE_MNEMONIC); - - const api = await ApiPromise.create({ provider: wsProvider }); - - const destinationErc20LRContract = ERC20PresetMinterPauser__factory.connect( - ERC20_TOKEN_ADDRESS, - wallet - ); - const destinationBalanceBefore = await destinationErc20LRContract.balanceOf( - EVM_DESTINATION_ADDRESS - ); - - const sourceBalanceBefore = ( - await api.query.assets.account(2000, account.address) - ).toHuman() as { balance: string }; - console.log(`Transferring 5 tokens from substrate to evm1.`); - console.log(`Sender (Alice): ${account.address}`); - console.log( - `Alice token balance on substrate network before:${sourceBalanceBefore.balance}` - ); - console.log( - `Alice token balance on evm1 network before:${destinationBalanceBefore.toString()}` - ); - - const assetTransfer = new SubstrateAssetTransfer(); - await assetTransfer.init(api, Environment.LOCAL); - - const transfer = await assetTransfer.createFungibleTransfer( - account.address, - EVM1_CHAIN_ID, - EVM_DESTINATION_ADDRESS, - RESOURCE_ID, - "5000000000000" // 12 Decimals - ); - - const fee = await assetTransfer.getFee(transfer); - - const transferTx = assetTransfer.buildTransferTransaction(transfer, fee); - - const unsub = await transferTx.signAndSend(account, ({ status }) => { - console.log(`Current status is ${status.toString()}`); - - if (status.isInBlock) { - console.log( - `Transaction included at blockHash ${status.asInBlock.toString()}` - ); - } else if (status.isFinalized) { - console.log( - `Transaction finalized at blockHash ${status.asFinalized.toString()}` - ); - unsub(); - } - - return; - }); - - console.log("Waiting for relayers to bridge transaction..."); - - let i = 0; - let destinationBalanceAfter: BigNumber; - for (; ;) { - await sleep(7000); - destinationBalanceAfter = await destinationErc20LRContract.balanceOf( - EVM_DESTINATION_ADDRESS - ); - if (!destinationBalanceAfter.eq(destinationBalanceBefore)) { - console.log("Transaction successfully bridged."); - break; - } - i++; - if (i > 5) { - // transaction should have been bridged already - console.log("transaction is taking too much time to bridge!"); - break; - } - } - - const balanceAfter = ( - await api.query.assets.account(2000, account.address) - ).toHuman() as { balance: string }; - - console.log( - `Alice token balance on substrate network after: ${balanceAfter.balance}` - ); - console.log( - `Alice token balance on evm1 network after: ${destinationBalanceAfter.toString()}` - ); - - return; -} - -const sleep = (ms: number): Promise => - new Promise((r) => setTimeout(r, ms)); - -// start specific example based on process arg -switch (process.argv[2]) { - case "1": - fungibleTransferFromEVM().finally(() => { }); - break; - case "2": - fungibleTransferFromSubstrate().finally(() => { }); - break; - default: - console.log("example not supported"); -} - diff --git a/examples/local-fungible-transfer/tsconfig.json b/examples/local-fungible-transfer/tsconfig.json deleted file mode 100644 index be09b38..0000000 --- a/examples/local-fungible-transfer/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "module": "ES2022", - "allowJs": true, - "declaration": true, - "sourceMap": true, - "declarationMap": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true, - "esModuleInterop": true, - "downlevelIteration": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - }, - "ts-node": { - "esm": true, - "experimentalSpecifierResolution": "node" - }, - "include": [ - "src" - ] -} \ No newline at end of file diff --git a/examples/substrate-to-evm-fungible-transfer/.env.sample b/examples/substrate-to-evm-fungible-transfer/.env.sample deleted file mode 100644 index 3f057ca..0000000 --- a/examples/substrate-to-evm-fungible-transfer/.env.sample +++ /dev/null @@ -1 +0,0 @@ -PRIVATE_MNEMONIC="YOUR TWELVE WORD MNEMONIC HERE WITH SPACES" \ No newline at end of file diff --git a/examples/substrate-to-evm-fungible-transfer/.gitignore b/examples/substrate-to-evm-fungible-transfer/.gitignore deleted file mode 100644 index 2eea525..0000000 --- a/examples/substrate-to-evm-fungible-transfer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.env \ No newline at end of file diff --git a/examples/substrate-to-evm-fungible-transfer/README.md b/examples/substrate-to-evm-fungible-transfer/README.md deleted file mode 100644 index 18e447b..0000000 --- a/examples/substrate-to-evm-fungible-transfer/README.md +++ /dev/null @@ -1,78 +0,0 @@ -## Sygma SDK Substrate Asset Transfer Example - -This is an example script that demonstrates the functionality of the SDK using the Sygma ecosystem. The script showcases a Substrate Asset transfer between Substrate and EVM using the Sygma SDK. - -## Prerequisites - -Before running the script, ensure that you have the following: - -- Node.js installed on your machine -- [Yarn](https://yarnpkg.com/) (version 3.4.1 or higher) -- Access to a Substrate node - -## Getting started - -### 1. Clone the repository - -To get started, clone this repository to your local machine with: - -```bash -git clone git@github.com:sygmaprotocol/sygma-sdk.git -cd sygma-sdk/ -``` - -### 2. Install dependencies - -Install the project dependencies by running: - -```bash -yarn install -``` - -### 3. Build the sdk - -To start the example you need to build the sdk first with: - -```bash -yarn sdk:build -``` - -## Usage - -This example uses the `dotenv` module to import the 12-word private mnemonic. To run the example, you will need to configure your environment variable to include your test development account's [12-word seed](https://support.polkadot.network/support/solutions/articles/65000169731-polkadot-extension-how-can-i-view-my-mnemonic-phrase-). A `.env.sample` is provided as a template. - -**DO NOT COMMIT YOUR MENOMONIC WITH REAL FUNDS TO GITHUB. DOING SO COULD RESULT IN COMPLETE LOSS OF YOUR FUNDS.** - -Create a `.env` file in the substrate-to-evm example folder: - -```bash -cd examples/substrate-to-evm-fungible-transfer -touch .env -``` - -Replace between the quotation marks your 12-word mnemonic: - -`PRIVATE_MNEMONIC="YOUR TWELVE WORD MNEMONIC HERE WITH SPACES"` - -To send a Substrate token to an EVM chain example transfer run: - -```bash -yarn run transfer -``` - -The example will use `@polkadot/keyring` in conjuction with the sygma-sdk to -create a transfer from `Roccoco Phala` to `Goerli`. - -Replace the placeholder values in the script with your own Substrate wallet mnemonic and destination EVM address. - -## Script Functionality - -This example script performs the following steps: - -- initializes the SDK and establishes a connection to the Substrate node. -- retrieves the list of supported domains and resources from the SDK configuration. -- Searches for the Substrate asset resource with the specified ResourceId -- Searches for the Goerli and Sepolia domains in the list of supported domains based on their chain IDs -- Constructs a transfer object that defines the details of the Substrate asset transfer -- Retrieves the fee required for the transfer from the SDK. -- Builds the final transfer transaction and sends it using the Substrate account. diff --git a/examples/substrate-to-evm-fungible-transfer/package.json b/examples/substrate-to-evm-fungible-transfer/package.json deleted file mode 100644 index 2c7b92a..0000000 --- a/examples/substrate-to-evm-fungible-transfer/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@buildwithsygma/sygma-sdk-substrate-to-evm-fungible-transfer-example", - "version": "0.1.0", - "license": "LGPL-3.0-or-later", - "description": "Sygma SDK Substrate Example", - "type": "module", - "sideEffects": false, - "repository": { - "type": "git", - "url": "https://github.com/sygmaprotocol/sygma-sdk" - }, - "keywords": [ - "sygma", - "sygmaprotocol", - "buildwithsygma", - "web3", - "bridge", - "ethereum" - ], - "scripts": { - "transfer": "ts-node src/transfer.ts" - }, - "author": "Sygmaprotocol Product Team", - "devDependencies": { - "dotenv": "^16.3.1", - "eslint": "8", - "eslint-config-prettier": "8.3.0", - "eslint-plugin-only-warn": "1.0.3", - "eslint-plugin-prettier": "4.0.0", - "ts-node": "10.9.1", - "typescript": "5.0.4" - }, - "dependencies": { - "@buildwithsygma/sygma-sdk-core": "workspace:*", - "@polkadot/api": "10.7.2", - "@polkadot/keyring": "12.2.1", - "@polkadot/util-crypto": "^12.2.1" - } -} diff --git a/examples/substrate-to-evm-fungible-transfer/src/transfer.ts b/examples/substrate-to-evm-fungible-transfer/src/transfer.ts deleted file mode 100644 index 93241e2..0000000 --- a/examples/substrate-to-evm-fungible-transfer/src/transfer.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { Keyring } from "@polkadot/keyring"; -import { ApiPromise, WsProvider } from "@polkadot/api"; -import { cryptoWaitReady } from "@polkadot/util-crypto"; -import dotenv from "dotenv"; -import { - Environment, - Substrate, - getTransferStatusData, -} from "@buildwithsygma/sygma-sdk-core"; - -dotenv.config(); - -const { SubstrateAssetTransfer } = Substrate; - -const GOERLI_CHAIN_ID = 5; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000001000"; -const MNEMONIC = process.env.PRIVATE_MNEMONIC; -const recipient = "0xD31E89feccCf6f2DE10EaC92ADffF48D802b695C"; - -if (!MNEMONIC) { - throw new Error("Missing environment variable: PRIVATE_MNEMONIC"); -} - -const getStatus = async ( - txHash: string -): Promise<{ status: string; explorerUrl: string } | void> => { - try { - const data = await getTransferStatusData(Environment.TESTNET, txHash); - - return data as { status: string; explorerUrl: string }; - } catch (e) { - console.log("error: ", e); - } -}; - -const substrateTransfer = async (): Promise => { - const keyring = new Keyring({ type: "sr25519" }); - // Make sure to fund this account with native tokens - // Account address: 5FNHV5TZAQ1AofSPbP7agn5UesXSYDX9JycUSCJpNuwgoYTS - - await cryptoWaitReady(); - - const account = keyring.addFromUri(MNEMONIC); - - const wsProvider = new WsProvider( - "wss://subbridge-test.phala.network/rhala/ws" - ); - const api = await ApiPromise.create({ provider: wsProvider }); - - const assetTransfer = new SubstrateAssetTransfer(); - - await assetTransfer.init(api, Environment.TESTNET); - - const transfer = await assetTransfer.createFungibleTransfer( - account.address, - GOERLI_CHAIN_ID, - recipient, - RESOURCE_ID, - "5000000000000" // 12 decimal places - ); - - const fee = await assetTransfer.getFee(transfer); - - const transferTx = assetTransfer.buildTransferTransaction(transfer, fee); - - const unsub = await transferTx.signAndSend(account, ({ status }) => { - console.log(`Current status is ${status.toString()}`); - - if (status.isInBlock) { - console.log( - `Transaction included at blockHash ${status.asInBlock.toString()}` - ); - } else if (status.isFinalized) { - console.log( - `Transaction finalized at blockHash ${status.asFinalized.toString()}` - ); - unsub(); - } - - let dataResponse: undefined | { status: string; explorerUrl: string }; - - const id = setInterval(() => { - getStatus(status.asInBlock.toString()) - .then((data) => { - if (data) { - dataResponse = data; - console.log(data); - } - }) - .catch(() => { - console.log("Transfer still not indexed, retrying..."); - }); - }, 5000); - - if (dataResponse && dataResponse.status === "executed") { - console.log("Transfer executed successfully"); - clearInterval(id); - process.exit(0); - } - }); -}; - -substrateTransfer() - .catch((e) => console.log(e)) - .finally(() => {}); diff --git a/examples/substrate-to-evm-fungible-transfer/tsconfig.json b/examples/substrate-to-evm-fungible-transfer/tsconfig.json deleted file mode 100644 index be09b38..0000000 --- a/examples/substrate-to-evm-fungible-transfer/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "module": "ES2022", - "allowJs": true, - "declaration": true, - "sourceMap": true, - "declarationMap": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true, - "esModuleInterop": true, - "downlevelIteration": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - }, - "ts-node": { - "esm": true, - "experimentalSpecifierResolution": "node" - }, - "include": [ - "src" - ] -} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index e4c2291..5261fbe 100644 --- a/yarn.lock +++ b/yarn.lock @@ -507,9 +507,25 @@ __metadata: languageName: unknown linkType: soft -"@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-example@workspace:examples/evm-to-evm-fungible-transfer": +"@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-example@workspace:examples/evm-to-evm-fungible-transfer-test": version: 0.0.0-use.local - resolution: "@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-example@workspace:examples/evm-to-evm-fungible-transfer" + resolution: "@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-example@workspace:examples/evm-to-evm-fungible-transfer-test" + dependencies: + "@buildwithsygma/sygma-sdk-core": "workspace:*" + dotenv: "npm:^16.3.1" + eslint: "npm:8" + eslint-config-prettier: "npm:8.3.0" + eslint-plugin-only-warn: "npm:1.0.3" + eslint-plugin-prettier: "npm:4.0.0" + ethers: "npm:5.6.2" + ts-node: "npm:10.9.1" + typescript: "npm:5.0.4" + languageName: unknown + linkType: soft + +"@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-text@workspace:examples/evm-to-evm-fungible-transfer": + version: 0.0.0-use.local + resolution: "@buildwithsygma/sygma-sdk-evm-to-evm-fungible-transfer-text@workspace:examples/evm-to-evm-fungible-transfer" dependencies: "@buildwithsygma/sygma-sdk-core": "workspace:*" dotenv: "npm:^16.3.1" @@ -6717,7 +6733,7 @@ __metadata: dependencies: bn.js: "npm:^4.11.8" ethereumjs-util: "npm:^6.0.0" - checksum: 25d2e1e5505d7df0683028a1b46b4c07d78f08ef38d20a93a4dbe18616479d3c314b5572bdf258605d70e939ac3fc01c893a3d97a4113a5a195ec39bf6ec4777 + checksum: dd1f7fad25f6c36fa34877176fdb10e21bfab5b88030fc427829f52686bcad3215168f55e5ed93689a1c34d0d802f39dec25b50ce1914da5b59c50d5975ae30e languageName: node linkType: hard