Costruisci su Dyneros

Esempi dApp

Esempi di codice completi e pronti per la produzione per costruire applicazioni su Dyneros Chain. Ogni esempio copre connessione, interazione e gestione degli errori.

Esempio 1 — Connetti Wallet

La base di ogni dApp: connessione a Dyneros Chain tramite MetaMask e cambio automatico della rete.

// connect.js — Connect MetaMask to Dyneros Chain
const DYNEROS_CHAIN = {
  chainId: "0x600D", // 24589 in hex
  chainName: "Dyneros Chain",
  nativeCurrency: { name: "DYN", symbol: "DYN", decimals: 18 },
  rpcUrls: ["https://mainnet.dyneros.com"],
  blockExplorerUrls: ["https://explorer.dyneros.com"]
};

async function connectWallet() {
  if (!window.ethereum) throw new Error("MetaMask not found");

  // Request accounts
  const accounts = await window.ethereum.request({
    method: "eth_requestAccounts"
  });

  // Switch to / add Dyneros Chain
  try {
    await window.ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: DYNEROS_CHAIN.chainId }]
    });
  } catch (err) {
    if (err.code === 4902) {
      // Chain not added yet — add it
      await window.ethereum.request({
        method: "wallet_addEthereumChain",
        params: [DYNEROS_CHAIN]
      });
    } else {
      throw err;
    }
  }

  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();
  return { provider, signer, address: accounts[0] };
}

// Usage
const { signer, address } = await connectWallet();
console.log("Connected:", address);

Esempio 2 — Trasferimento Token

Invia token dUSD ad un altro indirizzo con controllo del saldo e ascolto degli eventi.

// transfer.js — Send dUSD on Dyneros Chain
import { ethers } from "ethers";

const DUSD_ADDRESS = "0xfa69e3c56aCe1f93C6E332a656318Ba0Cc4d7e57";
const ERC20_ABI = [
  "function balanceOf(address) view returns (uint256)",
  "function transfer(address to, uint256 amount) returns (bool)",
  "function decimals() view returns (uint8)",
  "event Transfer(address indexed from, address indexed to, uint256 value)"
];

async function sendDUSD(signer, toAddress, amountHuman) {
  const dusd = new ethers.Contract(DUSD_ADDRESS, ERC20_ABI, signer);
  const decimals = await dusd.decimals();

  // Check balance
  const balance = await dusd.balanceOf(await signer.getAddress());
  const amount = ethers.parseUnits(amountHuman.toString(), decimals);

  if (balance < amount) {
    throw new Error(`Insufficient balance. Have: ${ethers.formatUnits(balance, decimals)} dUSD`);
  }

  // Send
  const tx = await dusd.transfer(toAddress, amount);
  console.log("TX sent:", tx.hash);

  // Wait for confirmation
  const receipt = await tx.wait();
  console.log("Confirmed in block:", receipt.blockNumber);

  return receipt;
}

// Usage
await sendDUSD(signer, "0xRecipient...", 50); // send 50 dUSD

Esempio 3 — Swap DEX

Uno swap completo da dUSD a WDYN usando il Router Dyneros, con quotazione del prezzo e tolleranza allo slippage.

// dex-swap.js — Swap dUSD for WDYN
import { ethers } from "ethers";

const ROUTER   = "0xD6c26Ce48bDe29bca596Abe5C3b3DF93C6b91F97";
const DUSD     = "0xfa69e3c56aCe1f93C6E332a656318Ba0Cc4d7e57";
const WDYN     = "0xd270c9AA03019c294c68e4Ea134995Cd30EC226b";

const ROUTER_ABI = [
  "function getAmountsOut(uint amountIn, address[] path) view returns (uint[] amounts)",
  "function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] path, address to, uint deadline) returns (uint[] amounts)"
];

const ERC20_APPROVE = ["function approve(address spender, uint256 amount) returns (bool)"];

async function swapDUSDforWDYN(signer, amountIn, slippagePct = 0.5) {
  const router = new ethers.Contract(ROUTER, ROUTER_ABI, signer);
  const path = [DUSD, WDYN];
  const amountInWei = ethers.parseEther(amountIn.toString());

  // Get price quote
  const amounts = await router.getAmountsOut(amountInWei, path);
  const expectedOut = amounts[1];
  const slippageFactor = 1 - (slippagePct / 100);
  const amountOutMin = expectedOut * BigInt(Math.floor(slippageFactor * 10000)) / 10000n;

  console.log(`Swap ${amountIn} dUSD → ~${ethers.formatEther(expectedOut)} WDYN`);

  // Approve router to spend dUSD
  const dusd = new ethers.Contract(DUSD, ERC20_APPROVE, signer);
  const approveTx = await dusd.approve(ROUTER, amountInWei);
  await approveTx.wait();

  // Execute swap
  const deadline = Math.floor(Date.now() / 1000) + 1200; // 20 min
  const swapTx = await router.swapExactTokensForTokens(
    amountInWei,
    amountOutMin,
    path,
    await signer.getAddress(),
    deadline
  );

  const receipt = await swapTx.wait();
  console.log("Swap complete. Block:", receipt.blockNumber);
  return receipt;
}

// Swap 100 dUSD with 0.5% slippage tolerance
await swapDUSDforWDYN(signer, 100, 0.5);

Example 4 — Deploy & Mint NFT

Distribuisci un semplice contratto ERC-721 su Dyneros Chain e mint token. Utile per certificati digitali, carte fedeltà e asset di gioco.

// DynerosNFT.sol — Minimal ERC-721
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract DynerosNFT is ERC721, Ownable {
    uint256 private _tokenId;
    mapping(uint256 => string) private _tokenURIs;

    constructor() ERC721("Dyneros NFT", "DNFT") Ownable(msg.sender) {}

    function mint(address to, string memory tokenURI) external onlyOwner returns (uint256) {
        _tokenId++;
        _mint(to, _tokenId);
        _tokenURIs[_tokenId] = tokenURI;
        return _tokenId;
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        return _tokenURIs[tokenId];
    }
}
// deploy-nft.js — Deploy and mint on Dyneros Chain
const { ethers } = require("hardhat");

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying from:", deployer.address);

  const NFT = await ethers.getContractFactory("DynerosNFT");
  const nft = await NFT.deploy();
  await nft.waitForDeployment();

  console.log("NFT contract deployed to:", await nft.getAddress());

  // Mint token #1
  const tx = await nft.mint(
    deployer.address,
    "https://metadata.dyneros.com/nft/1.json"
  );
  await tx.wait();
  console.log("Minted token #1 to:", deployer.address);
}

main().catch(console.error);

Esempio 5 — Binario di Pagamento

Un semplice contratto processore di pagamenti per uso enterprise — supporta pagamenti in batch, tracciamento fatture ed eventi di conferma.

// PaymentRail.sol — Enterprise payment processor
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract PaymentRail is Ownable {
    IERC20 public immutable dUSD;
    
    event PaymentSent(
        bytes32 indexed invoiceId,
        address indexed from,
        address indexed to,
        uint256 amount,
        uint256 timestamp
    );

    constructor(address _dUSD) Ownable(msg.sender) {
        dUSD = IERC20(_dUSD);
    }

    // Pay a specific invoice
    function pay(address to, uint256 amount, bytes32 invoiceId) external {
        require(amount > 0, "Amount must be > 0");
        dUSD.transferFrom(msg.sender, to, amount);
        emit PaymentSent(invoiceId, msg.sender, to, amount, block.timestamp);
    }

    // Batch pay multiple invoices
    function batchPay(
        address[] calldata recipients,
        uint256[] calldata amounts,
        bytes32[] calldata invoiceIds
    ) external {
        require(recipients.length == amounts.length, "Length mismatch");
        for (uint i = 0; i < recipients.length; i++) {
            dUSD.transferFrom(msg.sender, recipients[i], amounts[i]);
            emit PaymentSent(invoiceIds[i], msg.sender, recipients[i], amounts[i], block.timestamp);
        }
    }
}

Esempio 6 — Leggi Dati dalla Chain

Interroga saldi, dati di blocco e storico transazioni da Dyneros Chain usando ethers.js.

// read-chain.js — Query Dyneros Chain state
import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider("https://mainnet.dyneros.com");

// Current block
const block = await provider.getBlockNumber();
console.log("Current block:", block);

// Native DYN balance
const dynBalance = await provider.getBalance("0xYourAddress");
console.log("DYN balance:", ethers.formatEther(dynBalance));

// dUSD balance
const dusd = new ethers.Contract(
  "0xfa69e3c56aCe1f93C6E332a656318Ba0Cc4d7e57",
  ["function balanceOf(address) view returns (uint256)"],
  provider
);
const dusdBalance = await dusd.balanceOf("0xYourAddress");
console.log("dUSD balance:", ethers.formatEther(dusdBalance));

// Listen for new blocks
provider.on("block", (blockNumber) => {
  console.log("New block:", blockNumber);
});

Hai bisogno di un esempio specifico?

Contatta il team Dyneros se hai bisogno di un esempio di codice per il tuo caso d'uso specifico.