diff --git a/docs/03-sygma-sdk/02-Quick-Start/01-installing-the-sdk.md b/docs/03-sygma-sdk/02-Quick-Start/01-installing-the-sdk.md index fcefe01..8c6715f 100644 --- a/docs/03-sygma-sdk/02-Quick-Start/01-installing-the-sdk.md +++ b/docs/03-sygma-sdk/02-Quick-Start/01-installing-the-sdk.md @@ -9,16 +9,16 @@ draft: false The SDK is written in TypeScript and can be used in both Node.js and browser environment. -To install the [@buildwithsygma/sygma-sdk-core package](https://www.npmjs.com/package/@buildwithsygma/sygma-sdk-core), you can use either npm or yarn. To install using npm, run the following command: +To install the SDK, you can use either npm or yarn. To install using npm, run the following command: ```bash -npm install @buildwithsygma/sygma-sdk-core +npm install @buildwithsygma/core @buildwithsygma/evm @buildwithsygma/substrate ``` To install using yarn, run the following command: ```bash -yarn add @buildwithsygma/sygma-sdk-core +yarn add @buildwithsygma/core @buildwithsygma/evm @buildwithsygma/substrate ``` -That's it! Once you've installed the package, you can start using it in your project. \ No newline at end of file +That's it! Once you've installed the package, you can start using it in your project. diff --git a/docs/03-sygma-sdk/02-Quick-Start/02-evm-token-tranfers.md b/docs/03-sygma-sdk/02-Quick-Start/02-evm-token-tranfers.md index 214a68d..f25b2dc 100644 --- a/docs/03-sygma-sdk/02-Quick-Start/02-evm-token-tranfers.md +++ b/docs/03-sygma-sdk/02-Quick-Start/02-evm-token-tranfers.md @@ -11,92 +11,62 @@ draft: false In the examples below `Ethers` v5 was used. If you were to use v6, keep in mind the differences between versions. ::: -### Transferring a fungible asset between EVM chains +# Transferring a fungible asset between EVM chains -Transferring assets between EVM-based chains can be achieved using the Sygma SDK. +Transferring assets between EVM-based chains can be achieved using the Sygma SDK. To facilitate the transfer, the following steps are required: -To facilitate the transfer, the following steps are required: +1. Specify transfer parameters such as amount, recipient address, token, destination chain and use the method `createFungibleAssetTransfer` from `@buildwithsygma/evm` to create an instance of `FungibleAssetTransfer` +2. Check for any approvals required, and if required sign and broadcast these transactions. +3. Prepare, sign, and send the Transfer transaction to the Source network node -1. Create an instance of the `EvmAssetTransfer` object and initialize it. -2. Determine the fee for the transfer, using the EvmAssetTransfer `getFee()` method -3. Check for any approvals required, and if required sign and broadcast these transactions. -4. Prepare, sign, and send the `Transfer` transaction to the Source network node +## 1. Create and initialize the transfer object +To initialize the asset transfer object, the following parameters are required: -#### 1. Initialize the EvmAssetTransfer object +- An `EIP-1193` compatible EVM provider +- Environment variable `SYGMA_ENV` needs to be set as `mainnet` or `testnet` -To initialize the asset transfer object, the following parameters need to be supplied: - -- An instance of Ethers provider -- The environment in which the bridge should function - -```ts -const assetTransfer = new EvmAssetTransfer(); - -const provider = new JsonRpcProvider("https://URL-TO-YOUR-RPC") - -await assetTransfer.init( - provider, - Environment.TESTNET // (i.e. DEVNET, TESTNET, MAINNET) -); +```typescript +const fungibleTokenTransfer = await createFungibleAssetTransfer({ + source: 1, // Ethereum Mainnet + destination: 8453, // Base + sourceNetworkProvider: eip1193CompatibleProvider, + resource: + "0x0000000000000000000000000000000000000000000000000000000000000002", // ETH Resource ID can be found here: https://github.com/sygmaprotocol/sygma-shared-configuration/blob/0e3470df4935ae3cce8b44f496723070ff3b3d1c/mainnet/shared-config-mainnet.json + amount: BigInt(1) * BigInt(1e17), + recipientAddress: "", + sourceAddress: sourceAddress, // source wallet address +}); ``` -#### 2. Get fee - -To facilitate the transfer of tokens, a fee must be attached. This fee can be determined by utilizing the asset transfer `GetFee(transfer)` method. You will need to know the destination ChainID as well as the ResourceID that has been configured on the bridge. These details can be determined by inspecting the configurations of the bridge (see [here](https://docs.buildwithsygma.com/environments)) +## 2. Send Approval transactions -```ts -const wallet = new Wallet( - privateKey as string, // use the dotenv module to pull in a private key from a .env file - provider -); +You can check if approvals are required for your transfer. If there are approvals required for the transfer, you can sign the transaction and send it. -const transfer = await assetTransfer.createFungibleTransfer( - await wallet.getAddress(), - DESTINATION_CHAINID, - DESTINATION_ADDRESS, - RESOURCE_ID, - "AMOUNT" // use appropriate decimal places based on the token and/or ecosystem you are operating in -) - -const fee = await assetTransfer.getFee(transfer); +```typescript +const approvals = await fungibleTokenTransfer.getApprovalTransactions(); +for (const approval of approvals) { + const tx = await wallet.sendTransaction(approval); + await tx.wait(); +} ``` -#### 3. Check Approvals +## 3. Send transfer transaction -You can check if approvals are required for your transfer. If there are approvals required for the transfer and the `fee` has been obtained, you can sign the transaction and send it. +Once all the approvals have been confirmed you can finally send the actual fungible token transfer transaction. -```ts -// Build approvals given the `transfer` and `fee` parameters -const approvals = await assetTransfer.buildApprovals(transfer, fee); - -// Check if approvals are needed -for (const approval of approvals) { - const response = await wallet.sendTransaction( - approval as providers.TransactionRequest - ); - console.log("Sent approval with hash: ", response.hash); - } - -// Build the transfer transaction -const transferTx = await assetTransfer.buildTransferTransaction( - transfer, - fee - ); - -// Send the transaction using the wallet -const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); +```typescript +const transfer = await transfer.getTransferTransaction(); +const tx = await wallet.sendTransaction(transfer); +await tx.wait(); ``` -#### Check Transaction Hash +### Checking transaction hash -The `response` object returned by the `sendTransaction` method contains a `hash` property. This transaction hash is logged to the console, and it can be used to look up the transaction on a block explorer. +The response object returned by the `sendTransaction` method contains a hash property. This transaction hash is logged to the console, and it can be used to look up the transaction on a block explorer. -```ts -// Print the transaction hash - console.log("Sent transfer with hash: ", response.hash); +```typescript +console.log("Sent transfer with hash: ", tx.hash); ``` -A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/evm-to-evm-fungible-transfer/src/transfer.ts) \ No newline at end of file +A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/evm-to-evm-fungible-transfer/src/transfer.ts) diff --git a/docs/03-sygma-sdk/02-Quick-Start/03-substrate-token-transfer.md b/docs/03-sygma-sdk/02-Quick-Start/03-substrate-token-transfer.md index 5abada0..e9466ab 100644 --- a/docs/03-sygma-sdk/02-Quick-Start/03-substrate-token-transfer.md +++ b/docs/03-sygma-sdk/02-Quick-Start/03-substrate-token-transfer.md @@ -7,85 +7,41 @@ sidebar_position: 3 draft: false --- -### Transferring a fungible asset from Substrate to EVM +# Substrate to EVM Fungible token transfer -Transferring assets from Substrate-based chains to EVM-based chains can be achieved using the Sygma SDK. +Transferring assets from Substrate-based chains to EVM-based chains can be achieved using the Sygma SDK. To facilitate the transfer, the following steps are required: -To facilitate the transfer, the following steps are required: +1. Specify transfer parameters such as amount, recipient address, token, destination chain and use the method `createSubstrateFungibleAssetTransfer` from `@buildwithsygma/substrate` to create an instance of `SubstrateFungibleAssetTransfer` +2. Sign and send the transfer transaction using `polkadot.js` -1. Create an instance of the `SubstrateAssetTransfer` object and initialize it -2. Determine the fee for the transfer, using the SubstrateAssetTransfer `getFee()` method -3. Prepare, sign, and send the `Transfer` transaction to the Substrate node - -#### 1. Initialize the SubstrateAssetTransfer object +## 1. Create and initialize the transfer object To initialize the asset transfer object, the following parameters need to be supplied: -- An instance of the PolkadotJS ApiPromise object -- The environment in which the bridge should function - -```ts -const assetTransfer = new SubstrateAssetTransfer(); - -const wsProvider = new WsProvider("wss://URL-TO-YOUR-SUBSTRATE-INSTANCE"); - -// Create an instance of the PolkadotJS ApiPromise -const api = await ApiPromise.create({ provider: wsProvider }); - -await assetTransfer.init( - api, - Environment.TESTNET // (i.e. DEVNET, TESTNET, MAINNET) -); -``` - -#### 2. Get fee - -To facilitate the transfer of tokens, a fee must be attached. This fee can be determined by utilizing the asset transfer `GetFee(transfer)` method. You will need to know the destination ChainID as well as the ResourceID that has been configured on the bridge. These details can be determined by inspecting the configurations of the bridge (see [here](https://docs.buildwithsygma.com/environments)) - - -```ts - -const keyring = new Keyring({ type: "sr25519" }); -await cryptoWaitReady(); -const account = keyring.addFromUri(MNEMONIC); // use the dotenv module to pull in a mnemonic from a .env file -const transfer = await assetTransfer.createFungibleTransfer( - account.address, - DESTINATION_CHAINID, - DESTINATION_ADDRESS, - RESOURCE_ID, - "AMOUNT" // use appropriate decimal places based on the token and/or ecosystem you are operating in -) - -const fee = await assetTransfer.getFee(transfer); - +- An instance of the PolkadotJS `ApiPromise` object +- Environment variable `SYGMA_ENV` needs to be set as `mainnet` or `testnet` + +```typescript +const fungibleTokenTransfer = await createSubstrateFungibleAssetTransfer({ + source: 5232, // Phala + destination: 1, // Ethereum Mainnet + sourceNetworkProvider: apiPromise, + sourceAddress: "", + resource: + "0x0000000000000000000000000000000000000000000000000000000000000001", // PHA resource ID more resources can be found here: https://github.com/sygmaprotocol/sygma-shared-configuration/blob/main/mainnet/shared-config-mainnet.json + amount: BigInt(1) * BigInt(1e12), + destinationAddress: "", +}); ``` -#### Prepare the transfer transaction - -Now that the fee has been determined, the transaction to deposit assets into the bridge should be generated, signed, and broadcast to the network. - -```ts -// Build the transfer transaction - const transferTx = assetTransfer.buildTransferTransaction( - transfer, - fee - ); +## 2. Sign and send transfer transaction -// Sign and broadcast the transfer transaction -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(); - } +```typescript +const tx = await fungibleTokenTransfer.getTransferTransaction(); +await transferTx.signAndSend(account, (results) => { + const { status } = results; + console.log(`Current status is ${status.toString()}`); }); ``` -A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/substrate-to-evm-fungible-transfer/src/transfer.ts) \ No newline at end of file +A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/substrate-to-evm-fungible-transfer/src/transfer.ts) diff --git a/docs/03-sygma-sdk/02-Quick-Start/04-gmp.md b/docs/03-sygma-sdk/02-Quick-Start/04-gmp.md index 36743f1..469123a 100644 --- a/docs/03-sygma-sdk/02-Quick-Start/04-gmp.md +++ b/docs/03-sygma-sdk/02-Quick-Start/04-gmp.md @@ -11,79 +11,49 @@ draft: false In the examples below `Ethers` v5 was used. If you were to use v6, keep in mind the differences between versions. ::: -### Transferring a message between EVM chains +# Generic Message Passing (GMP) -Generic messages can be transferred between EVM chains using the Sygma SDK. +Generic messages can be transferred between EVM chains using the Sygma SDK. To facilitate the transfer, the following steps are required: -To facilitate the transfer, the following steps are required: +1. Specify generic message transfer parameters and create an instance of `GenericMessageTransfer` using `createCrossChainContractCall` method from `@buildwithsygma/evm` package. +2. Sign and send the transfer transaction. -1. Create an instance of the `EVMGenericMessageTransfer` object and initialize it. -2. Determine the fee for the transfer, using the `EVMGenericMessageTransfer.getFee()` method -3. Prepare, sign, and send the Transfer transaction to the Source network node +There are a few requirements for the Destination chain contract function that gets called. Refer to the [Generic Message Passing documentation](../../02-sygma-protocol/06-generic.md) for details. -The `executeDeposit` function prepares and populates a deposit transaction. The key parameter is `depositData`, which is a string requiring a specific format. Refer to the [Generic Message Passing](../../02-sygma-protocol/06-generic.md) documentation for instructions on how to format the `depositData` string correctly. - -There are a few requirements for the Destination chain contract function that gets called. Refer to the [Generic Message Passing](../../02-sygma-protocol/06-generic.md) documentation for details. - -#### 1. Initialize the EvmAssetTransfer object +## 1. Create and initialize the transfer object To initialize the generic message transfer object, the following parameters need to be supplied: -- An instance of Ethers provider -- The environment in which the bridge should function - -```ts -const messageTransfer = new EVMGenericMessageTransfer(); - -const sourceProvider = new providers.JsonRpcProvider( - "https://URL-TO-YOUR-RPC" -); -const destinationProvider = new providers.JsonRpcProvider( - "https://URL-TO-YOUR-RPC" -); - - await messageTransfer.init( - sourceProvider, - Environment.TESTNET // (i.e. DEVNET, TESTNET, MAINNET) - ); -``` - -#### 2. Get fee - -To facilitate the transfer of a generic message, a fee must be paid. This fee can be determined by utilizing the `messageTransfer.getFee(transfer)` method. You will need to know the destination ChainID as well as the ResourceID that has been configured on the bridge. These details can be determined by inspecting the configurations of the bridge (see [here](https://docs.buildwithsygma.com/environments)) - - -```ts -const wallet = new Wallet( - privateKey ?? "", // use the dotenv module to pull in a private key from a .env file - sourceProvider - ); - -const transfer = messageTransfer.createGenericMessageTransfer( - await wallet.getAddress(), - DESTINATION_CHAINID, - RESOURCE_ID, - DESTINATION_CONTRACT_ADDRESS, // contract address you are calling to - DESTINATION_FUNCTION_SIGNATURE, // function signature you are invoking cross-chain - EXECUTION_DATA, // the actual data payload that the smart contract function is expecting - MAX_FEE -) - -const fee = await messageTransfer.getFee(transfer); +- An `EIP-1193` compatible EVM provider +- Environment variable `SYGMA_ENV` needs to be set as `mainnet` or `testnet` +- Address, `ABI` of the contract and the function that will be invoked on the destination chain. + +```typescript +const gmpTransfer = await createCrossChainContractCall< + typeof sepoliaBaseStorageContract, + "store" +>({ + gasLimit: BigInt(0), + functionParameters: ["0x", "0x", BigInt(1)], + functionName: "store", + destinationContractAbi: sepoliaBaseStorageContract, + destinationContractAddress: "0x4bE595ab5A070663B314970Fc10C049BBA0ad489", + maxFee: BigInt("3000000"), + source: 11155111, // Sepolia + destination: 84532, // Base Sepolia + sourceNetworkProvider: eip1193CompatibleProvider, + sourceAddress: "", + resource: + "0x0000000000000000000000000000000000000000000000000000000000000600", +}); ``` -### 3. Prepare, sign, and send the Transfer transaction to the Source network node -```ts -const transferTx = await messageTransfer.buildTransferTransaction( - transfer, - fee - ); +## 2. Sign and send the transfer transaction -// Send the transaction using the wallet - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: ", response.hash); +```typescript +const transaction = await gmpTransfer.getTransferTransaction(); +const tx = await wallet.sendTransaction(transaction); +await tx.wait(); ``` -A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/evm-to-evm-generic-mesage-passing/src/transfer.ts) \ No newline at end of file +A full example of the above can be found [here](https://github.com/sygmaprotocol/sygma-sdk/blob/main/examples/evm-to-evm-generic-message-transfer/src/transfer.ts) diff --git a/docs/03-sygma-sdk/03-Advanced/01-local-setup.md b/docs/03-sygma-sdk/03-Advanced/01-local-setup.md index e23ab4d..7c33d9f 100644 --- a/docs/03-sygma-sdk/03-Advanced/01-local-setup.md +++ b/docs/03-sygma-sdk/03-Advanced/01-local-setup.md @@ -14,25 +14,25 @@ You will need to have Docker and Docker Compose installed and running on your ma ### Local Sygma Setup The local setup contains preconfigured resources including: + - two EVM networks running on Ganache with Sygma contracts already deployed - The networks are named `EVM1` and `EVM2` respectively - one Substrate network with Sygma pallets already implemented - The network is named `Substrate` -- three relayer instances listening for, voting, and executing on events -- a fee oracle +- three relayer instances listening for, voting, and executing on events +- a fee oracle -More details can be found in the local configuration. +More details can be found in the local configuration. -To interact with the local setup using the Sygma SDK, select `LOCAL` environment on initialization of the `assetTransfer` object. +To interact with the local setup using the Sygma SDK, set `SYGMA_ENV` environment variable as `local`. -```ts -const assetTransfer = new EVMAssetTransfer(); -await assetTransfer.init(provider, Environment.LOCAL); +```sh +export SYGMA_ENV="local" ``` ### Running the local setup example -We will be running the local setup example provided inside the [Sygma SDK repository](https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/local-fungible-transfer). +We will be running the example provided inside the [Sygma SDK repository](https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-evm-fungible-transfer). #### 1) Clone the Sygma Relayer repository @@ -44,7 +44,7 @@ git clone https://github.com/sygmaprotocol/sygma-relayer.git #### 2) Start local setup -`cd` into the cloned sygma-relayer folder, and then run the following command, which will start the dockerized setup: +`cd` into the cloned sygma-relayer folder, and then run the following command, which will start the dockerized setup: ``` make example @@ -74,26 +74,25 @@ yarn install And build the SDK by running: ``` -yarn sdk:build +yarn build ``` #### 4) Run the EVM-to-Substrate token transfer example -`cd` into the `local-fungible-transfer` example inside the `/sygma-sdk/examples` folder, and run: +1. `cd` into the `evm-to-substrate-fungible-transfer` example inside the `/sygma-sdk/examples` folder +2. Update RPC URLs and transfer parameters in the example with local configuration + +3. run: ```bash -yarn run transfer:evm-substrate +yarn run transfer ``` This will start a local ERC-20 transfer of the `ERC20LRTest` token using the local Sygma setup. It will use `ethers` together with the sygma-sdk to create a transfer from the `EVM1` network to the `Substrate` network. #### 5) Run the Substrate-to-EVM token transfer example -To demonstrate the exact same transfer in the other direction, you can also run: - -```bash -yarn run transfer:substrate-evm -``` +To demonstrate the exact same transfer in the other direction, you can use the example `substrate-to-evm-fungible-transfer` and follow similar steps of the previous example. Similarly, this will use `@polkadot/api` together with the sygma-sdk to create an `ERC20LRTest` transfer from the `Substrate` network to the `EVM1` network. @@ -105,11 +104,11 @@ To easily verify the bridging transactions, we have added console logs that will TODO - add information on all registered resources on local setup --> ### Make changes to onchain Sygma setup -Once you start the local setup, it is possible to configure the Sygma EVM contracts or Sygma Substrate pallets, since all node RPC endpoints are exposed and you can interact with them as with any regular node. -| Network | RPC endpoint | -| --------- | ---------------------------| -| EVM1 | http://127.0.0.1:8545 | -| EVM2 | http://127.0.0.1:8547 | -| Substrate | ws://127.0.0.1:9944 | +Once you start the local setup, it is possible to configure the Sygma EVM contracts or Sygma Substrate pallets, since all node RPC endpoints are exposed and you can interact with them as with any regular node. +| Network | RPC endpoint | +| --------- | --------------------- | +| EVM1 | http://127.0.0.1:8545 | +| EVM2 | http://127.0.0.1:8547 | +| Substrate | ws://127.0.0.1:9944 | diff --git a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/01-EVM-EVM-example.md b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/01-EVM-EVM-example.md index ed237dd..1c862bb 100644 --- a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/01-EVM-EVM-example.md +++ b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/01-EVM-EVM-example.md @@ -1,6 +1,6 @@ --- slug: /sdk/examples/erc20/evm-example -id: examples-erc20-evm-example +id: examples-erc20-evm-example title: EVM To EVM Token Transfer description: Section that describes how to perform an EVM to EVM token transfer. sidebar_position: 1 @@ -9,10 +9,9 @@ draft: false ### EVM-to-EVM token transfer example -In the following example, we will use the `TESTNET` environment to perform a cross-chain ERC-20 transfer with 5 `ERC20LRTST` tokens. The transfer will be initiated on the EVM-side via the Cronos testnet and received on the EVM-side via the Sepolia Ethereum testnet. +In the following example, we will use the `TESTNET` environment to perform a cross-chain ERC-20 transfer with 1 testnet `USDC` token. The transfer will be initiated on the EVM-side via the Cronos testnet and received on the EVM-side via the Sepolia Ethereum testnet. -This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts. The complete example can be found in this [repo]( -https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-evm-fungible-transfer). +This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts. The complete example can be found in this [repo](https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-evm-fungible-transfer). ### Prerequisites @@ -21,11 +20,11 @@ Before running the script, ensure that you have the following: - Node.js v18 - Yarn (version 3.4.1 or higher) - The [exported private key](https://support.metamask.io/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key) of your development wallet -- Testnet [CRO](https://docs.cronos.org/for-users/testnet-faucet) for gas +- Testnet ETH for gas - An Ethereum [provider](https://www.infura.io/) (in case the hardcoded RPC within the script does not work) - A development wallet funded with `ERC20LRTest` tokens from the [Sygma faucet](https://faucet-ui-stage.buildwithsygma.com/) (you can use the UI below; please allow some time for minting as testnet may be congested) -import App from '../../../../src/Faucet/App'; +import App from '../../../../src/Faucet/App';
@@ -36,7 +35,7 @@ We make use of the dotenv module to manage exported private keys with environmen ### Getting started -1. Clone the repository +1. Clone the repository Clone the sygma-sdk repository into a directory of your choice, and then `cd` into the folder: @@ -46,7 +45,7 @@ cd sygma-sdk/ ``` 2. Install dependencies - + Install the project dependencies by running: ```bash @@ -58,12 +57,12 @@ yarn install Build the SDK by running the following command: ```bash -yarn sdk:build +yarn build ``` 4. 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. +This example uses the `dotenv` module to retrieve 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.** @@ -77,7 +76,7 @@ touch .env Replace between the quotation marks your exported private key: `PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE"` - + To send an ERC-20 example transfer from EVM to EVM, run: ```bash @@ -91,111 +90,91 @@ The example will use `ethers` in conjunction with the sygma-sdk to create a tran This example script performs the following steps: -- Initializes the SDK by importing the required packages and defining the constants for the script. +- Import required libraries from the dependencies. ```ts -import { EVMAssetTransfer, Environment, getTransferStatusData, TransferStatusResponse } from "@buildwithsygma/sygma-sdk-core"; +import { getSygmaScanLink, type Eip1193Provider } from "@buildwithsygma/core"; +import { + createFungibleAssetTransfer, + FungibleTransferParams, +} from "@buildwithsygma/evm"; +import dotenv from "dotenv"; import { Wallet, providers } from "ethers"; - -const SEPOLIA_CHAIN_ID = 11155111; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000000300"; // This is the resource ID for the ERC20LRTEST token according to Sygma's testnet environment -const CRONOS_RPC_URL = process.env.CRONOS_RPC_URL || "https://evm-t3.cronos.org" // use your own provider in case this RPC URL does not work -const getStatus = async ( - txHash: string -): Promise => { - const data = await getTransferStatusData(Environment.TESTNET, txHash); - return data as TransferStatusResponse[]; -}; +import Web3HttpProvider from "web3-providers-http"; ``` -- Configures the dotenv module and sets the `privateKey` as a value to be pulled from the `.env` file. +- Read contents of the `.env` file using `dotenv`. The script throws an error if the private key is not provided ```ts -import dotenv from "dotenv"; - -dotenv.config() - +dotenv.config(); const privateKey = process.env.PRIVATE_KEY; - -if (!privateKey) { - throw new Error("Missing environment variable: PRIVATE_KEY"); -} +if (!privateKey) throw new Error("Missing environment variable: PRIVATE_KEY"); ``` -- Defines the ERC-20 transfer function. +- Define transfer constants like destination chain ID, source chain ID, recipient address, resource ID and RPC URLs ```ts -export async function erc20Transfer(): Promise { +const SEPOLIA_CHAIN_ID = 11155111; +const BASE_SEPOLIA_CHAIN_ID = 84532; +const RESOURCE_ID = + "0x0000000000000000000000000000000000000000000000000000000000001200"; +const SEPOLIA_RPC_URL = + process.env.SEPOLIA_RPC_URL || "https://ethereum-sepolia-rpc.publicnode.com"; ``` -- Set up the provider, wallet, and asset transfer objects using the TESTNET environment. +- Constant and function to retrieve explorer URL (Optional) ```ts - const provider = new providers.JsonRpcProvider(CRONOS_RPC_URL); - const wallet = new Wallet(privateKey ?? "", provider); - const assetTransfer = new EVMAssetTransfer(); - await assetTransfer.init(provider, Environment.TESTNET); +const explorerUrls: Record = { + [SEPOLIA_CHAIN_ID]: "https://sepolia.etherscan.io", +}; +const getTxExplorerUrl = (params: { + txHash: string; + chainId: number; +}): string => `${explorerUrls[params.chainId]}/tx/${params.txHash}`; ``` -- Constructs a `transfer` object that defines the details of the ERC-20 token transfer using the previously declared constants, as well as the amount to be transferred. As we specify the `getAddress` method from the ethers.js `wallet` module for our recipient, the recipient will be the same address but on a different test network. - +- Create Ethereum provider and wallet to be able to send transactions and query data + ```ts - const transfer = 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, so in this case, 5 tokens would be sent - ); +const web3Provider = new Web3HttpProvider(SEPOLIA_RPC_URL); +const ethersWeb3Provider = new providers.Web3Provider(web3Provider); +const wallet = new Wallet(privateKey ?? "", ethersWeb3Provider); +const sourceAddress = await wallet.getAddress(); +const destinationAddress = await wallet.getAddress(); ``` -- Retrieves the fee required to complete 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 ERC-20 tokens. +- Prepare fungible token transfer parameters and create a transfer object ```ts -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 params: FungibleTransferParams = { + source: SEPOLIA_CHAIN_ID, + destination: BASE_SEPOLIA_CHAIN_ID, + sourceNetworkProvider: web3Provider as unknown as Eip1193Provider, + resource: RESOURCE_ID, + amount: BigInt(1) * BigInt(1e6), + recipientAddress: destinationAddress, + sourceAddress: sourceAddress, + environment: Environment.TESTNET, +}; + +const transfer = await createFungibleAssetTransfer(params); ``` -- Invokes the `getTransferStatusData` and `getStatus` functions by taking the transaction hash as an input to periodically check the status of the cross-chain transaction. +- Get and complete approval transactions ```ts -const id = setInterval(() => { - getStatus(response.hash) - .then((data) => { - if (data[0]) { - console.log("Status of the transfer", data[0].status); - if(data[0].status == "executed") { - clearInterval(id); - process.exit(0); - } - } else { - console.log("Waiting for the TX to be indexed"); - } - }) - .catch((e) => { - console.log("error:", e); - }); - }, 5000); +const approvals = await transfer.getApprovalTransactions(); +for (const approval of approvals) { + const response = await wallet.sendTransaction(approval); + await response.wait(); } ``` -- Builds the final `transfer` transaction and sends it using the Ethereum wallet. - +- Complete the transfer transaction + ```ts - const transferTx = await assetTransfer.buildTransferTransaction( - transfer, - fee - ); - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: ", response.hash); -} -``` \ No newline at end of file +const transferTx = await transfer.getTransferTransaction(); +const response = await wallet.sendTransaction(transferTx); +await response.wait(); +``` diff --git a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/02-EVM-Substrate-example.md b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/02-EVM-Substrate-example.md index 45c7eb0..15c2cc9 100644 --- a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/02-EVM-Substrate-example.md +++ b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/02-EVM-Substrate-example.md @@ -1,6 +1,6 @@ --- slug: /sdk/examples/erc20/evm-substrate-example -id: examples-erc20-evm-substrate-example +id: examples-erc20-evm-substrate-example title: EVM To Substrate Token Transfer description: Section that describes how to perform an EVM to Substrate token transfer. sidebar_position: 2 @@ -13,10 +13,9 @@ Please be aware that the Rococo-Phala testnet is currently down due to ongoing m ### EVM-to-Substrate token transfer example -In the following example, we will use the `TESTNET` environment to perform a cross-chain ERC-20 transfer with 0.5 Sepolia sygUSD `sygUSD` tokens. The transfer will be initiated on the EVM-side via the Sepolia Ethereum testnet and received on the Substrate-side via the Rococo-Phala testnet. +In the following example, we will use the `TESTNET` environment to perform a cross-chain ERC-20 transfer with 1.00 Sepolia sygUSD `sygUSD` tokens. The transfer will be initiated on the EVM-side via the Sepolia Ethereum testnet and received on the Substrate-side via the Tangle testnet. -This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts/pallets. The complete example can be found in this [repo]( -https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-substrate-fungible-transfer#sygma-sdk-erc20-example). +This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts/pallets. The complete example can be found in this [repo](https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-substrate-fungible-transfer#sygma-sdk-erc20-example). ### Prerequisites @@ -26,11 +25,11 @@ Before running the script, ensure that you have the following: - Yarn (version 3.4.1 or higher) - The [exported private key](https://support.metamask.io/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key) of your development wallet - A Substrate wallet to receive tokens into (the example presets an existing wallet address already) -- [Sepolia ETH](https://sepoliafaucet.com/) for gas +- [Sepolia ETH](https://sepoliafaucet.com/) for gas - An Ethereum [provider](https://www.infura.io/) (in case the hardcoded RPC within the script does not work) - A development wallet funded with `sygUSD` tokens from the [Sygma faucet](https://faucet-ui-stage.buildwithsygma.com/) -import App from '../../../../src/Faucet/App'; +import App from '../../../../src/Faucet/App';
@@ -41,7 +40,7 @@ We make use of the dotenv module to manage exported private keys with environmen ### Getting started -1. Clone the repository +1. Clone the repository Clone the sygma-sdk repository into a directory of your choice, and then `cd` into the folder: @@ -51,7 +50,7 @@ cd sygma-sdk/ ``` 2. Install dependencies - + Install the project dependencies by running: ```bash @@ -63,7 +62,7 @@ yarn install Build the SDK by running the following command: ```bash -yarn sdk:build +yarn build ``` 4. Usage @@ -84,7 +83,7 @@ Replace between the quotation marks your exported private key: `PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE"` Replace the placeholder value in the script for `DESTINATION_ADDRESS` with your preferred destination Substrate address. - + To send an ERC-20 example transfer from EVM to Substrate, run: ```bash @@ -92,118 +91,96 @@ cd examples/evm-to-substrate-fungible-transfer yarn run transfer ``` -The example will use `ethers` in conjunction with the sygma-sdk to create a transfer from Sepolia to Rococo-Phala with a `sygUSD` token. It will be received on Rococo-Phala as the `sygUSD` token. +The example will use `ethers` in conjunction with the Sygma SDK to create a transfer from Sepolia to Rococo-Phala with a `sygUSD` token. It will be received on Rococo-Phala as the `sygUSD` token. ### Script functionality This example script performs the following steps: -- Initializes the SDK by importing the required packages and defining the constants for the script. +- Import required libraries from the dependencies. ```ts -import { EVMAssetTransfer, Environment, getTransferStatusData, TransferStatusResponse } from "@buildwithsygma/sygma-sdk-core"; +import { getSygmaScanLink, type Eip1193Provider } from "@buildwithsygma/core"; +import { + createFungibleAssetTransfer, + FungibleTransferParams, +} from "@buildwithsygma/evm"; +import dotenv from "dotenv"; import { Wallet, providers } from "ethers"; - -const ROCOCO_PHALA_CHAIN_ID = 5231; -const DESTINATION_ADDRESS = "5CDQJk6kxvBcjauhrogUc9B8vhbdXhRscp1tGEUmniryF1Vt"; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000001100"; -const SEPOLIA_RPC_URL = process.env.SEPOLIA_RPC_URL || "https://gateway.tenderly.co/public/sepolia" // use your another RPC URL in case this does not work -const getStatus = async ( - txHash: string -): Promise => { - const data = await getTransferStatusData(Environment.TESTNET, txHash); - return data as TransferStatusResponse[]; -}; +import Web3HttpProvider from "web3-providers-http"; ``` -- Configures the dotenv module and sets the `privateKey` as a value to be pulled from the `.env` file. +- Read contents of the `.env` file using `dotenv`. The script throws an error if the private key is not provided ```ts -import dotenv from "dotenv"; - -dotenv.config() - +dotenv.config(); const privateKey = process.env.PRIVATE_KEY; - -if (!privateKey) { - throw new Error("Missing environment variable: PRIVATE_KEY"); -} +if (!privateKey) throw new Error("Missing environment variable: PRIVATE_KEY"); ``` -- Defines the ERC-20 transfer function. +- Define transfer constants like destination chain ID, source chain ID, recipient address, resource ID and RPC URLs ```ts -export async function erc20Transfer(): Promise { +const SEPOLIA_CHAIN_ID = 11155111; +const TANGLE_CHAIN_ID = 3799; +const RESOURCE_ID = + "0x0000000000000000000000000000000000000000000000000000000000001100"; +const SEPOLIA_RPC_URL = + process.env.SEPOLIA_RPC_URL || "https://ethereum-sepolia-rpc.publicnode.com"; ``` -- Set up the provider, wallet, and asset transfer objects using the TESTNET environment. + +- Constant and function to retrieve explorer URL (Optional) ```ts -export async function erc20Transfer(): Promise { - const provider = new providers.JsonRpcProvider(SEPOLIA_RPC_URL); - const wallet = new Wallet(privateKey ?? "", provider); - const assetTransfer = new EVMAssetTransfer(); - await assetTransfer.init(provider, Environment.TESTNET); +const explorerUrls: Record = { + [SEPOLIA_CHAIN_ID]: "https://sepolia.etherscan.io", +}; +const getTxExplorerUrl = (params: { + txHash: string; + chainId: number; +}): string => `${explorerUrls[params.chainId]}/tx/${params.txHash}`; ``` -- Constructs a `transfer` object that defines the details of the ERC-20 token transfer using the previously declared constants, as well as the amount to be transferred. - +- Create Ethereum provider and wallet to be able to send transactions and query data + ```ts - const transfer = assetTransfer.createFungibleTransfer( - await wallet.getAddress(), - ROCOCO_PHALA_CHAIN_ID, - DESTINATION_ADDRESS, - RESOURCE_ID, - "500000" // 6 decimal places, so in this case, 0.5 sygUSD tokens - ); +const web3Provider = new Web3HttpProvider(SEPOLIA_RPC_URL); +const ethersWeb3Provider = new providers.Web3Provider(web3Provider); +const wallet = new Wallet(privateKey ?? "", ethersWeb3Provider); +const sourceAddress = await wallet.getAddress(); +const destinationAddress = await wallet.getAddress(); ``` -- Retrieves the fee required to complete 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 ERC-20 tokens. +- Prepare fungible token transfer parameters and create a transfer object ```ts - 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 params: FungibleTransferParams = { + source: SEPOLIA_CHAIN_ID, + destination: TANGLE_CHAIN_ID, + sourceNetworkProvider: web3Provider as unknown as Eip1193Provider, + resource: RESOURCE_ID, + amount: BigInt(1) * BigInt(1e6), + recipientAddress: "", +}; + +const transfer = await createFungibleAssetTransfer(params); ``` -- Invokes the `getTransferStatusData` and `getStatus` functions by taking the transaction hash as an input to periodically check the status of the cross-chain transaction. + +- Get and complete approval transactions ```ts - const id = setInterval(() => { - getStatus(response.hash) - .then((data) => { - if (data[0]) { - console.log("Status of the transfer", data[0].status); - if(data[0].status == "executed") { - clearInterval(id); - process.exit(0); - } - } else { - console.log("Waiting for the TX to be indexed"); - } - }) - .catch((e) => { - console.log("error:", e); - }); - }, 5000); +const approvals = await transfer.getApprovalTransactions(); +for (const approval of approvals) { + const response = await wallet.sendTransaction(approval); + await response.wait(); } ``` -- Builds the final `transfer` transaction and sends it using the Ethereum wallet. - +- Complete the transfer transaction + ```ts - const transferTx = await assetTransfer.buildTransferTransaction( - transfer, - fee - ); - const response = await wallet.sendTransaction( - transferTx as providers.TransactionRequest - ); - console.log("Sent transfer with hash: ", response.hash); -} -``` \ No newline at end of file +const transferTx = await transfer.getTransferTransaction(); +const response = await wallet.sendTransaction(transferTx); +await response.wait(); +``` diff --git a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/03-Substrate-EVM-example.md b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/03-Substrate-EVM-example.md index 8cfe913..688f050 100644 --- a/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/03-Substrate-EVM-example.md +++ b/docs/03-sygma-sdk/04-Examples/01-Basic-ERC-20-Token-Transfers/03-Substrate-EVM-example.md @@ -1,6 +1,6 @@ --- slug: /sdk/examples/erc20/substrate-evm-example -id: examples-erc20-substrate-evm-example +id: examples-erc20-substrate-evm-example title: Substrate To EVM Token Transfer description: Section that describes how to perform a Substrate to EVM token transfer. sidebar_position: 3 @@ -11,7 +11,6 @@ draft: false Please be aware that the Rococo-Phala testnet is currently down due to ongoing maintenance by the Phala team as they migrate their testnet to Paseo. Stay tuned for further updates. ::: - ### EVM-to-Substrate token transfer example In the following example, we will use the `TESTNET` environment to perform a cross-chain ERC-20 transfer with 0.5 sygUSD `sygUSD` tokens. The transfer will be initiated on the Substrate-side via the Rococo-Phala testnet and received on the EVM-side via the Sepolia Ethereum testnet. @@ -29,7 +28,7 @@ Before running the script, ensure that you have the following: - A Substrate provider (in case the hardcoded WSS within the script does not work) - A Substrate development wallet funded with `sygUSD` tokens -import App from '../../../../src/Faucet/App'; +import App from '../../../../src/Faucet/App';
@@ -40,7 +39,7 @@ We make use of the dotenv module to manage Substrate's private mnemonics with en ### Getting started -1. Clone the repository +1. Clone the repository Clone the sygma-sdk repository into a directory of your choice, and then `cd` into the folder: @@ -50,7 +49,7 @@ cd sygma-sdk/ ``` 2. Install dependencies - + Install the project dependencies by running: ```bash @@ -62,7 +61,7 @@ yarn install Build the SDK by running the following command: ```bash -yarn sdk:build +yarn build ``` 4. Usage @@ -83,7 +82,7 @@ Replace between the quotation marks your 12-word mnemonic: `PRIVATE_MNEMONIC="YOUR TWELVE WORD MNEMONIC HERE WITH SPACES"` Replace the placeholder value in the script for `recipient` with your preferred destination EVM address. - + To send a Substrate token transfer from Substrate to EVM, run: ```bash @@ -100,118 +99,87 @@ This example script performs the following steps: - Initializes the SDK by importing the required packages and defining the constants for the script. ```ts -import { Keyring } from "@polkadot/keyring"; +import type { SubstrateAssetTransferRequest } from "@buildwithsygma/substrate"; +import { createSubstrateFungibleAssetTransfer } from "@buildwithsygma/substrate"; import { ApiPromise, WsProvider } from "@polkadot/api"; +import { Keyring } from "@polkadot/keyring"; import { cryptoWaitReady } from "@polkadot/util-crypto"; import dotenv from "dotenv"; -import { - Environment, - Substrate, - getTransferStatusData, - TransferStatusResponse -} from "@buildwithsygma/sygma-sdk-core"; - -const { SubstrateAssetTransfer } = Substrate; -const SEPOLIA_CHAIN_ID = 11155111; -const RESOURCE_ID = - "0x0000000000000000000000000000000000000000000000000000000000001100"; // this is the resourceID for sygUSD const MNEMONIC = process.env.PRIVATE_MNEMONIC; -const recipient = "0xD31E89feccCf6f2DE10EaC92ADffF48D802b695C"; // replace this value for your preferred EVM recipient address -const RHALA_RPC_URL = process.env.RHALA_RPC_URL || "wss://rhala-node.phala.network/ws" if (!MNEMONIC) { throw new Error("Missing environment variable: PRIVATE_MNEMONIC"); } -``` -- Configures the dotenv module and sets the `MNEMONIC` as a value to be pulled from the `.env` file. +const SEPOLIA_CHAIN_ID = 11155111; +const TANGLE_CHAIN_ID = 3799; -```ts -import dotenv from "dotenv"; +const RESOURCE_ID_SYGMA_USD = + "0x0000000000000000000000000000000000000000000000000000000000002000"; +const recipient = ""; +const TANGLE_RPC_URL = + process.env.SOURCE_SUBSTRATE_RPC_URL ?? "wss://rpc.tangle.tools"; +``` -dotenv.config(); +Note: In the case of a substrate transfer, mnemonic is required. -const MNEMONIC = process.env.PRIVATE_MNEMONIC; +- Constant and function to retrieve Sygma scanner URL (Optional) -if (!MNEMONIC) { - throw new Error("Missing environment variable: PRIVATE_MNEMONIC"); -} +```ts +const SYGMA_EXPLORER_URL = "https://scan.test.buildwithsygma.com"; +const getSygmaExplorerTransferUrl = (params: { + blockNumber: number; + extrinsicIndex: number; +}): string => + `${SYGMA_EXPLORER_URL}/transfer/${params.blockNumber}-${params.extrinsicIndex}`; ``` -- Defines the main Substrate transfer function, including the connection to the blockchain using a WebSocket provider, initializing the asset transfer instance, and setting up the keyring and account from the mnemonic phrase. +- Create substrate provider and wallet to be able to send transactions and query data ```ts -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(RHALA_RPC_URL); - const api = await ApiPromise.create({ provider: wsProvider }); - - const assetTransfer = new SubstrateAssetTransfer(); - - await assetTransfer.init(api, Environment.TESTNET); +const keyring = new Keyring({ type: "sr25519" }); +await cryptoWaitReady(); +const account = keyring.addFromUri(MNEMONIC); +const wsProvider = new WsProvider(TANGLE_RPC_URL); +const api = await ApiPromise.create({ provider: wsProvider }); ``` -- Invokes the `getTransferStatusData` and `getStatus` functions by taking the transaction hash as an input to periodically check the status of the cross-chain transaction. +- Prepare fungible token transfer parameters and create a transfer object ```ts -const id = setInterval(() => { - getStatus(status.asInBlock.toString()) - .then((data) => { - if (data[0]) { - console.log("Status of the transfer", data[0].status); - if(data[0].status == "executed") { - clearInterval(id); - process.exit(0); - } - } else { - console.log("Waiting for the TX to be indexed"); - } - }) - .catch((e) => { - console.log("error:", e); - }); - }, 5000); - }); +const transferParams: SubstrateAssetTransferRequest = { + source: TANGLE_CHAIN_ID, + destination: SEPOLIA_CHAIN_ID, + sourceNetworkProvider: api, + sourceAddress: account.address, + resource: RESOURCE_ID_SYGMA_USD, + amount: BigInt(1) * BigInt(1e18), + destinationAddress: recipient, + environment: process.env.SYGMA_ENV, }; ``` -- Constructs a transfer object that calculates the fee, then builds, signs, and sends the transaction. +- Send the transaction and wait for confirmation ```ts -const transferTx = assetTransfer.buildTransferTransaction(transfer, fee); +const transfer = await createSubstrateFungibleAssetTransfer(transferParams); +const transferTx = await transfer.getTransferTransaction(); - const unsub = await transferTx.signAndSend(account, ({ status }) => { - console.log(`Current status is ${status.toString()}`); +const unsub = await transferTx.signAndSend(account, (results) => { + const { status } = results; - if (status.isInBlock) { - console.log( - `Transaction included at blockHash ${status.asInBlock.toString()}` - ); - } else if (status.isFinalized) { + if (status.isFinalized) { + const blockNumber = results.blockNumber?.toNumber(); + const extrinsicIndex = results.txIndex; + + if (blockNumber && extrinsicIndex) { console.log( - `Transaction finalized at blockHash ${status.asFinalized.toString()}` + `Explorer URL: ${getSygmaExplorerTransferUrl({ + blockNumber, + extrinsicIndex, + })}` ); - unsub(); } -``` - -- Logs the current status of the transaction, and if it's included in a block or finalized, outputs the respective block hash. - -```ts -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(); } }); -``` \ No newline at end of file +``` diff --git a/docs/03-sygma-sdk/04-Examples/02-GMP-Examples/01-GMP-Example-With-A-Simple-Storage-Contract.md b/docs/03-sygma-sdk/04-Examples/02-GMP-Examples/01-GMP-Example-With-A-Simple-Storage-Contract.md index eccb5d7..ea00754 100644 --- a/docs/03-sygma-sdk/04-Examples/02-GMP-Examples/01-GMP-Example-With-A-Simple-Storage-Contract.md +++ b/docs/03-sygma-sdk/04-Examples/02-GMP-Examples/01-GMP-Example-With-A-Simple-Storage-Contract.md @@ -1,6 +1,6 @@ --- slug: /sdk/examples/gmp/evm-example-gmp -id: examples-gmp-evm-example-gmp +id: examples-gmp-evm-example-gmp title: GMP Example With A Simple Storage Contract description: An EVM to EVM example of GMP sidebar_position: 1 @@ -9,10 +9,9 @@ draft: false ### GMP Example With A Simple Storage Contract -In the following example, we will use the `TESTNET` environment to pass a generic message from Ethereum Sepolia to Base-Sepolia Testnet using a simple storage contract. Specifically, the `deposit` method will be called on Sepolia, passing the details of the function to be called (the `store` function, or function signature `0xa271ced2`) on a smart contract deployed on Base-Sepolia ([0x669f52487ffa6f9abf722082f735537a98ec0e4b](https://sepolia.basescan.org/address/0x669f52487ffa6f9abf722082f735537a98ec0e4b)). The method will encode the current UNIX timestamp as the payload to be passed and stored in the destination chain contract. The data can be read by calling the `retrieve` function on the destination chain contract by querying the depositor address derived from the private key. +In the following example, we will use the `TESTNET` environment to pass a generic message from Ethereum Sepolia to Base-Sepolia Testnet using a storage contract. Specifically, the `deposit` method will be called on Sepolia, passing the details of the function to be called on a smart contract deployed on Base-Sepolia ([0x4bE595ab5A070663B314970Fc10C049BBA0ad489](https://sepolia.basescan.org/address/0x4bE595ab5A070663B314970Fc10C049BBA0ad489)). The method will encode an address and an arbitrary number as the payload to be passed and stored in the destination chain contract. The data can be read by calling the `retrieve` function on the destination chain contract by querying the depositor address derived from the private key. -This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts. The complete example can be found in this [repo]( -https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-evm-generic-mesage-passing). +This is an example script that demonstrates the functionality of the Sygma SDK and the wider Sygma ecosystem of relayers and bridge and handler contracts. The complete example can be found in this [repo](https://github.com/sygmaprotocol/sygma-sdk/tree/main/examples/evm-to-evm-generic-message-transfer). ### Prerequisites @@ -20,7 +19,7 @@ Before running the script, ensure that you have the following: - Node.js v18 - Yarn (version 3.4.1 or higher) -- A development wallet funded with [Sepolia ETH](https://sepolia-faucet.pk910.de/) for gas +- A development wallet funded with [Sepolia ETH](https://sepolia-faucet.pk910.de/) for gas - The [exported private key](https://support.metamask.io/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key) of your development wallet - An Ethereum [provider](https://www.infura.io/) (in case the hardcoded RPC within the script does not work) @@ -30,7 +29,7 @@ We make use of the dotenv module to manage exported private keys with environmen ### Getting Started -1. Clone the repository +1. Clone the repository Clone the sygma-sdk repository into a directory of your choice, and then `cd` into the folder: @@ -40,7 +39,7 @@ cd sygma-sdk/ ``` 2. Install dependencies - + Install the project dependencies by running: ```bash @@ -52,7 +51,7 @@ yarn install Build the SDK by running the following command: ```bash -yarn sdk:build +yarn build ``` 4. Usage @@ -61,10 +60,10 @@ This example uses the `dotenv` module to manage private keys. To run the example **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-evm GMP example folder: +Create a `.env` file in the `evm-to-evm-generic-message-transfer` folder within examples: ```bash -cd examples/evm-to-evm-generic-mesage-passing +cd examples/evm-to-evm-generic-message-transfer touch .env ``` @@ -72,14 +71,13 @@ Replace between the quotation marks your exported private key: `PRIVATE_KEY="YOUR_PRIVATE_KEY_HERE"` -To call the function on the destination chain contract, `cd` into the example folder `examples/evm-to-evm-generic-mesage-passing` and run: +To call the function on the destination chain contract, `cd` into the example folder `examples/evm-to-evm-generic-message-transfer` and run: ```bash -cd examples/evm-to-evm-generic-mesage-passing +cd examples/evm-to-evm-generic-message-transfer yarn run transfer ``` The example will use `ethers` in conjunction with the sygma-sdk to call a function on a smart contract on Base-Sepolia 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. -