Giter Club home page Giter Club logo

acala.js's Introduction

license npm

@acala-network

This library provides additional typing information for user to access Acala Network by using polkadot.js.

Getting Started

More documentation and examples on wiki.

  • Install dependencies
yarn add @polkadot/api @acala-network/api@beta
  • Create API instance
import { ApiPromise } from '@polkadot/api';
import { WsProvider } from '@polkadot/rpc-provider';
import { options } from '@acala-network/api';

async function main() {
    const provider = new WsProvider('wss://karura.api.onfinality.io/public-ws');
    const api = new ApiPromise(options({ provider }));
    await api.isReady;

    // use api
}

main()
  • Use api to interact with node
// query and display account data
const data = await api.query.system.account('5F98oWfz2r5rcRVnP9VCndg33DAAsky3iuoBSpaPUbgN9AJn');
console.log(data.toHuman())

Packages

  • api
    • Contains necessary options to create a polkadot.js API instance
  • types
    • Polkadot.js type definations for Acala Network

acala.js's People

Contributors

actions-user avatar qwer951123 avatar xlc avatar ntduan avatar shengda avatar nnnnnnnnnni avatar ermalkaleci avatar shunjizhan avatar shaunxw avatar sasha-nechaiev avatar eliasmpw avatar zjb0807 avatar bette7 avatar ukby1234 avatar gluneau avatar jhutchings1 avatar

Stargazers

 avatar davpal avatar Michael Bennett avatar Will Pankiewicz avatar  avatar Victoria Kapitonenko avatar jgadipriss avatar Haruki Kondo avatar eNddy avatar Jeru avatar Tomasz Waszczyk avatar Crystal_Alchemist avatar  avatar  avatar  avatar FengFeng avatar  avatar Xtian avatar Eclésio Junior avatar Leouarz avatar Tom Robiquet avatar Hans Struwig avatar  avatar Genz avatar  avatar  avatar Simone Romano avatar Josh Echeverri avatar  avatar drbh avatar jlca avatar  avatar Victor Nascimento avatar Saad Ahmed avatar  avatar  avatar  avatar alex avatar Stéphane P avatar Max Kravchuk avatar Jordy (Jordan) Lee avatar misoobu avatar mhusnirizal avatar Alyasin Achmad Naruto avatar Kevin Gislason avatar Cheng JIANG avatar pk avatar EGOR avatar Dima avatar Lucas Nicolas Pelloni avatar Web3 Capital avatar ampersandi avatar  avatar skyh24 avatar KooFrank avatar  avatar 0xThreeBody avatar

Watchers

Ruitao Su avatar James Cloos avatar  avatar  avatar pk avatar Muhammad-Jibril B.A. (Khalifa MBA) avatar  avatar 0xThreeBody avatar

acala.js's Issues

Cannot decode block 44075 with the latest type bundle

I was trying to get event data for block 44075 on Karura but see the following error:

2021-07-02 18:03:47        RPC-CORE: getStorage(key: StorageKey, at?: BlockHash): StorageData:: Unable to decode storage system.events:: createType(Vec<EventRecord>):: decodeU8a: failed at 0x00020000003c013c… on : {"phase":"Phase","event":"Event","topics":"Vec<Hash>"}:: decodeU8a: failed at 0x3c013ce0c400003d… on event: {"index":"EventId","data":"Null"}:: Struct: failed on data: (PalletsOrigin,ScheduleTaskIndex):: decodeU8a: failed at 0x3ce0c400003d0005… on : {"_enum":{"System":"SystemOrigin","Timestamp":"Null","RandomnessCollectiveFlip":"Null","Balances":"Null","Accounts":"Null","Currencies":"Null","Tokens":"Null","Vesting":"Null","AcalaTreasury":"Null","Utility":"Null","Multisig":"Null","Recovery":"Null","Proxy":"Null","Scheduler":"Null","Indices":"Null","GraduallyUpdate":"Null","Authorship":"Null","Babe":"Null","Grandpa":"Null","Staking":"Null","Session":"Null","Historical":"Null","GeneralCouncil":"CollectiveOrigin","GeneralCouncilMembership":"Null","HonzonCouncil":"CollectiveOrigin","HonzonCouncilMembership":"Null","HomaCouncil":"CollectiveOrigin","HomaCouncilMembership":"Null","TechnicalCommittee":"CollectiveOrigin","TechnicalCommitteeMembership":"Null","Authority":"DelayedOrigin","ElectionsPhragmen":"Null","AcalaOracle":"Null","BandOracle":"Null","OperatorMembershipAcala":"Null","OperatorMembershipBand":"Null","Auction":"Null","Rewards":"Null","OrmlNFT":"Null","Prices":"Null","Dex":"Null","AuctionManager":"Null","Loans":"Null","Honzon":"Null","CdpTreasury":"Null","CdpEngine":"Null","EmergencyShutdown":"Null","Homa":"Null","NomineesElection":"Null","StakingPool":"Null","PolkadotBridge":"Null","Incentives":"Null","AirDrop":"Null","NFT":"Null","RenVmBridge":"Null","Contracts":"Null","EVM":"Null","Sudo":"Null","TransactionPayment":"Null"}}:: Unable to create Enum via index 60, in System, Timestamp, RandomnessCollectiveFlip, Balances, Accounts, Currencies, Tokens, Vesting, AcalaTreasury, Utility, Multisig, Recovery, Proxy, Scheduler, Indices, GraduallyUpdate, Authorship, Babe, Grandpa, Staking, Session, Historical, GeneralCouncil, GeneralCouncilMembership, HonzonCouncil, HonzonCouncilMembership, HomaCouncil, HomaCouncilMembership, TechnicalCommittee, TechnicalCommitteeMembership, Authority, ElectionsPhragmen, AcalaOracle, BandOracle, OperatorMembershipAcala, OperatorMembershipBand, Auction, Rewards, OrmlNFT, Prices, Dex, AuctionManager, Loans, Honzon, CdpTreasury, CdpEngine, EmergencyShutdown, Homa, NomineesElection, StakingPool, PolkadotBridge, Incentives, AirDrop, NFT, RenVmBridge, Contracts, EVM, Sudo, TransactionPayment

I am using the latest type definitions from https://github.com/AcalaNetwork/acala.js/tree/master/packages/type-definitions/src/json

tokens_queryExistentialDeposit not decorated in 2.3.3

Description

When using acala.js the following line is printed whenever I connect to a provider:

2022-02-21 15:16:30        API/INIT: RPC methods not decorated: tokens_queryExistentialDeposit

Tested on ghcr.io/acalanetwork/karura-runtime:pr-1914 (v2.3.3)

Steps to recreate

image
image

image

Unsafe member access in sdk/utils/storage/storage.js

While calling getAllIncentivePools, I get the following error:

2022-12-19 14:03:53        API/INIT: RPC methods not decorated: evm_blockLimits, transaction_unstable_submitAndWatch, transaction_unstable_unwatch
/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:46
      return queryPath.reduce((acc, i) => {
                       ^
TypeError: Cannot read properties of undefined (reading 'entries')
    at /Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:50:19
    at Array.reduce (<anonymous>)
    at SubStorage.getQuery (/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:46:24)
    at SubStorage.subscribeWithPromiseApi (/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:91:23)
    at SubStorage.subscribe (/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:30:12)
    at new SubStorage (/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:23:10)
    at Function.create (/Users/user/proj/node_modules/@acala-network/sdk/utils/storage/storage.js:161:24)
    at Object.dexSavingRewardRates (/Users/user/proj/node_modules/@acala-network/sdk/incentive/storages.js:17:31)
    at /Users/user/proj/node_modules/@acala-network/sdk/incentive/index.js:35:28
    at Incentive.memoized [as dexSavingRewardRates$] (/Users/user/proj/node_modules/@polkadot/util/cjs/memoize.js:35:41)
[nodemon] app crashed - waiting for file changes before starting...

Relevant code:

    const provider: any = new WsProvider('wss://karura-rpc-0.aca-api.network');
    const api: any = new ApiPromise(options({ provider }));
    await api.isReady;
    const wallet = new Wallet(api);
    await wallet.isReady;

    let ict = new Incentive({ api, wallet })
    let liq = new Liquidity(api, wallet)
    let ips = await ict.getAllIncentivePools()

I'm using the following versions of acala/polkadot dependencies:

"dependencies": {
    "@acala-network/sdk": "4.1.8-9",
    "@acala-network/sdk-core": "4.1.8-9",
    "@acala-network/api": "4.1.8-9",
    "@acala-network/eth-providers": "^2.5.4",
    "@acala-network/type-definitions": "4.1.8-9",
    "@polkadot/api": "^9.9.1",
    "@polkadot/typegen": "^9.9.1",
    "@polkadot/types-codec": "^9.9.1",
    "@polkadot/api-derive": "^9.9.1"
}

Cannot retrieve data on an uninitialized chain

dependencies:

"dependencies": {
    "@acala-network/api": "^3.0.2",
    "@clover-network/node-types": "1.0.4",
    "@polkadot/api": "^6.5.2",
    "@phala/typedefs": "^0.2.29",
    "commander": "^8.1.0",
    "express": "^4.17.1",
    "fs-extra": "^10.0.0",
    "jsutility": "../jsutility",
    "log4js": "^6.3.0",
    "moonbeam-types-bundle": "^1.2.7",
    "npm": "^6.14.15"
  }
invoke function fail ["",{},"Error: Cannot retrieve data on an uninitialized chain
    at assert (./node_modules/@polkadot/util/assert.cjs:34:11)
    at ApiPromise._getBlockRegistry (./substrateProxy/node_modules/@polkadot/api/base/Init.cjs:216:22)
    at ApiPromise.getBlockRegistry (./node_modules/@polkadot/api/base/Init.cjs:281:22)
    at ./node_modules/@polkadot/api/base/Init.cjs:130:53
    at RpcCore.memoized (./node_modules/@polkadot/util/memoize.cjs:33:41)
    at callWithRegistry (./node_modules/@polkadot/rpc-core/bundle.cjs:252:214)
    at Observable._subscribe (./node_modules/@polkadot/rpc-core/bundle.cjs:265:9)
    at Observable._trySubscribe (./node_modules/rxjs/dist/cjs/internal/Observable.js:41:25)
    at ./node_modules/rxjs/dist/cjs/internal/Observable.js:35:31
    at Object.errorContext (./node_modules/rxjs/dist/cjs/internal/util/errorContext.js:22:9)"] stack:Error
    at Log.error (/usr/local/work/chainProxy/jsutility/log_util/index.js:64:15)
    at SubstrateProxy.<anonymous> (./substrate.js:450:36)
    at Generator.throw (<anonymous>)
    at rejected (./substrate.js:25:65)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

how can i fix this

initializing Swap sdk Promise is throwing error

import { SwapPromise } from '@acala-network/sdk-swap';
const swapPromise = new SwapPromise(api);

Uncaught (in promise) TypeError: (0 , _util.memoize) is not a function
at new SwapPromise (swap-promise.js:21:1)

Acala vs Karura swap sdk

Do Acala and Karura have the same swap SDK? We are unable to find dApps in github repositories.

We are implementing the XCM router package and we wish to map every native exchange to give users the ability to swap while XCM.

Thank you in advance.

StorageKey Parsing: REGISTRY: Unable to resolve type AcalaPrimitivesCurrencyTokenSymbol

We are trying to parse StorageKeys with the AcalaAPI from the "Tokens" Pallet / "Accounts" StorageMap with the following code

{

    const { ApiPromise } = require("@polkadot/api");
    const { WsProvider } = require("@polkadot/rpc-provider");
    const { Metadata, TypeRegistry, StorageKey, decorateStorage } = require('@polkadot/types');
    var p = 'tokens';
    var s = 'accounts';
    var k = "0x99971b5749ac43e0235e41b0d37869188ee7418a6531173d60d1f6a82d8f4d51f99116aca57aa49df451550cc0032f6be6b912626c9dfa3cd9e65b4412b19eb9d123edb1aa22d492a58a88091c483a7ad62f83b2dd5937360081";
    var v = "0xab974d437a6fd80000000000000000000000000000000000000000000000000000000000000000000000000000000000";

    const provider = new WsProvider("wss://karura-rpc-0.aca-api.network");
    const { options } = require("@acala-network/api");
    var api = new ApiPromise(options({ provider }));
    await api.isReady;

    var rpcDataV14 = await api.rpc.state.getMetadata()
    const registry = new TypeRegistry();
    const metadata = new Metadata(registry, rpcDataV14);
    registry.setMetadata(metadata);
    const query = decorateStorage(registry, metadata.asLatest, metadata.version);

    var queryMeta = query[p][s].meta;

    // key                                                                                                                                                                                                         
    try {
        var key = new StorageKey(registry, k);

        // **** ERROR: REGISTRY: Unable to resolve type AcalaPrimitivesCurrencyTokenSymbol, it will fail on construction                                                                                           
        key.setMeta(queryMeta);


        var pk = key.toHuman();
        console.log(pk);
    } catch (err) {
        console.log("PK ERR", err);
    }
}


parseStorageKey();

However, we are getting an error:

REGISTRY: Unable to resolve type AcalaPrimitivesCurrencyTokenSymbol, it will fail on construction

at the point of the setMeta call. We are able to parse StorageKey values from Polkadot/Kasuma chains using the above strategy for many other pallets (e.g. "System"/"Account" etc.), and are able to parse the StorageData (v) from the Karura chain. However, there appears to be something we are missing above.

The expected parse of the StorageKey should have an accountID and token (or in more advanced cases, Dex Token pairs).

Missing Decoration

When connecting to the RPC, following decoration is missing:

2022-07-25 09:32:28        API/INIT: RPC methods not decorated: evm_blockLimits
2022-07-25 09:32:28        API/INIT: Not decorating unknown runtime apis: 0xe3df3f2aa8a5cc57/2

Exposing RPCs as part of the types bundle

In https://github.com/AcalaNetwork/acala.js/blob/master/packages/type-definitions/src/index.ts#L127 you have this -

const bundle = {
  types: [...versioned].map((version) => {
    return {
      minmax: version.minmax,
      types: {
        ...types,
        ...version.types
      }
    };
  }),
  alias: typesAlias
};

I would suggest adding the RPCs in there as well as defined just before -

const bundle = {
  rpc,
  types: [...versioned].map((version) => {
    return {
      minmax: version.minmax,
      types: {
        ...types,
        ...version.types
      }
    };
  }),
  alias: typesAlias
};

Cross Chain SDK

How To Use

1. Init SDK

// for karura-kusama cross-chains,
const karuraAdapter = new KaruraAdapter(karuraWalletSDK);
const kusamaAdapter = new KusmaAdapter(kusamaApi);

const crossChain = new CrossChain({
  adapters: [
    acalaAdapter,
    kusamaAdapter
  ]
});

2. Query Available Destination Chains

...init cross-chain SDK

const dests = crossChain.getDestiantionChains({ from: 'karura' });

3. Query Available From Chains

...init cross-chain SDK

const froms = crossChain.getFromChains({ to: 'karura' });

4. Query Available Tokens

...init cross-chain SDK

const tokens = crossChain.getAvailableTokens({ from: 'karura', to: 'kusama' });

5. Query Transfer Configs

transfer configs contain the important information for the cross-chain transfer

name desc
token the token on origin chain
balance the token balances on origin chain
warnings some warning messages for the transfer
errors some errors for the transfer if have
available will be true when no errors
minInput the minimum amount used for user input
maxInput the maximum amount used for user input
showKeepAlive a switch to control whether display keepalive toggle
destinationED the existential deposits config on destination chain
destinationFee.fee the fee amount charged on the destination chain
destinationFee.token the fee token charged on the destination chain
...init cross-chain SDK

const ksm = await wallet.getToken('KSM');
const transferConfigs = await crossChain.getTransferConfigs({
  from: 'karura',
  to: 'kusama',
  account: ACCOUNT,
  token: ksm
});

crossChain.subscribeTransferConfigs({
  from: 'karura',
  to: 'kusama',
  account: ACCOUNT,
  token: ksm
}).subscribe({
  next: ...do somethings.
});

6. Create Cross Chain Transfer

const transfer = crossChain.createTransfer({
  from: 'karura',
  to: 'kusama',
  account: string,
  amount: new FixedpointNumber(1, 12)
});

await transfer.tx.signAndSend(ACCOUNT)

7. Subscribe Cross Chain Transfer Success Or Not

NOTICES:

  1. subscribe cross-chain transfer status need setup destination chain adapter
  2. judged based on the balance change, not very accurate
const transfer = crossChain.createTransfer({
  from: 'karura',
  to: 'kusama',
  account: string,
  amount: new FixedpointNumber(1, 12),
});

await transfer.tx.signAndSend(ACCOUNT)

transfer.watch({
  timeout: 3 * 60 * 1000 // will wait 3 mins for checking destiantion balance change
}).subscribe({
  next: () => {
    // do something
  }
})

How To Support A New Chain

  1. add chain data at configschains.tx
  2. add CrossChainAdapter by creating a new adapters/[CHIAN_NAME]Dapter.ts file
  3. implement the adapter
  • propertes:
    1. chain
    2. routers
  • methods:
    1. subscrineEnv
      subscribe the transfer environments include min/max input amount, token ED.etc.
    2. getCrossChainFeeConfigs
      get the cross-chain fee configs
    3. subscribeBalance
      subscribe the balance informations for token
    4. createTx
      used for create cross-chain transfer

API Manager

  • speed ​​measure
  • support connect the fastest endpoint
  • return promise/rxjs api
  • support report the endpoint health status
  • support manager multiply chains

polkadot.js.org errors decoding block 493009

Polkadot.js explorer is failing to decode block 493009. Navigating to the link https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fkarura-rpc-1.aca-api.network#/explorer/query/493009

gives

Unable to retrieve the specified block details. createType(SignedBlock):: Struct: failed on block: {"header":"Header","extrinsics":"Vec<Extrinsic>"}:: Struct: failed on extrinsics: Vec<Extrinsic>:: createType(ExtrinsicV4):: createType(ExtrinsicSignatureV4):: decodeU8a: failed at 0x0f012472f4c57b61… on signature: {"_enum":{"Ed25519":"Ed25519Signature","Sr25519":"Sr25519Signature","Ecdsa":"EcdsaSignature"}}:: Unable to create Enum via index 15, in Ed25519, Sr25519, Ecdsa

Probably due to the recent type updates for Kusama

Add additional types for prototype Starport Module

The Prototype Starport module has been added to the Mandala Runtime. For the Polkadot.js website to work, additional types will need to be added to interface with the Mandala chain.

There's a new "CASH" TokenSymbol with the value of 140

"TokenSymbol": {
  "_enum": {
   ....
    "CASH": 140
  }
},

There are also some additional Datatypes and Enums that needs to be added.

"CashYieldIndex": "u128",
"GatewayNoticePayload": {
 "_enum": {
   "SetSupplyCap": "(CurrencyId, Balance)",
   "ChangeAuthorities": "Vec<CompoundAuthoritySignature>",
   "Unlock": "(CurrencyId, Balance, AccountId)",
   "SetFutureYield": "(Balance, CashYieldIndex, Moment)"
 }
},
"GatewayNotice": {
 "id": "u64",
 "payload": "GatewayNoticePayload"
},
"CompoundAuthoritySignature": "AccountId"

improve auto generated types

current auto generated types aren't exact enough, for example, setCollateralParams has it's interest_rate_per_sec as any type, but it's real type should be Option<u128>.

This can result in that decoding failed when TS types are "correct", for example

      const interestRatePerSec: BigNumber;

      provider.api.tx.cdpEngine.setCollateralParams(
        { Token: 'DOT' },
        { NewValue: interestRatePerSec },
        ...
      )

this will throw

Error: createType(Call):: Call: failed decoding cdpEngine.setCollateralParams:: Struct: failed on args: {"currency_id":"{\"_enum\":{\"Token\":\"AcalaPrimitivesCurrencyTokenSymbol\",\"DexShare\":\"(AcalaPrimitivesCurrencyDexShare,AcalaPrimitivesCurrencyDexShare)\",\"Erc20\":\"H160\",\"StableAssetPoolToken\":\"u32\",\"LiquidCrowdloan\":\"u32\",\"ForeignAsset\":\"u16\"}}","interest_rate_per_sec":"{\"_enum\":{\"NoChange\":\"Null\",\"NewValue\":\"Option<u128>\"}}","liquidation_ratio":"{\"_enum\":{\"NoChange\":\"Null\",\"NewValue\":\"Option<u128>\"}}","liquidation_penalty":"{\"_enum\":{\"NoChange\":\"Null\",\"NewValue\":\"Option<u128>\"}}","required_collateral_ratio":"{\"_enum\":{\"NoChange\":\"Null\",\"NewValue\":\"Option<u128>\"}}","maximum_total_debit_value":"{\"_enum\":{\"NoChange\":\"Null\",\"NewValue\":\"u128\"}}"}:: Struct: failed on interest_rate_per_sec: {"_enum":{"NoChange":"Null","NewValue":"Option<u128>"}}:: Enum(NewValue):: Unable to construct number from multi-key object

looks like essentially a @polkadot/typegen issue

Cannot swap tokens

I'm trying to swap between different pairs (KAR -> KUSD, KAR -> KINT, KINT -> KUSD etc.) with @acala-network/sdk-swap or with swapWithExactSupply or with swapWithExactTarget doesn't matter.

but in most cases (about 8 times of 10) I'm not receiving tokens and API shows it, but

  1. it takes commission in any result, success or fail
  2. why it doesn't swap tickets ?
const polkadotApi = await getPolkadotApiProvider();

 const karuraWallet = new WalletPromise(polkadotApi);
 const signer = await getSigner();
 const slippage = new FixedPointNumber(1);

 const KAR = karuraWallet.getToken("KAR");
 const KINT = karuraWallet.getToken("KINT");

 const path = [KAR, KINT];
 const supplyAmount = new FixedPointNumber(1, KAR.decimals);
 const swapPromise = new SwapPromise(polkadotApi);

 const parameters = await swapPromise.swap(path, supplyAmount, "EXACT_INPUT");

 const beforeKARBalance = await karuraWallet.queryBalance(signer.address, KAR);
 const beforeKINTBalance = await karuraWallet.queryBalance(
   signer.address,
   KINT
 );

 await polkadotApi.tx.dex
   .swapWithExactSupply(
     path.map((item) => item.toChainData()),
     supplyAmount.toChainData(),
     parameters.output.balance.mul(slippage).toChainData()
   )
   .signAndSend(signer, async (result) => {
     if (result.isInBlock) {
       const afterKARBalance = await karuraWallet.queryBalance(
         signer.address,
         KAR
       );
       const afterKINTBalance = await karuraWallet.queryBalance(
         signer.address,
         KINT
       );

       console.log(`
KAR AFTER: ${afterKARBalance.freeBalance.toString()}
KINT AFTER: ${afterKINTBalance.freeBalance.toString()}
RECEIVE: ${afterKINTBalance.freeBalance
         .sub(beforeKINTBalance.freeBalance)
         .toString()}
   `);
     }
   });

sdk-core and sdk-swap not working as per documentation

I am trying to import getPresentToken and SwapTrade from their respective packages but it seems you guys have removed them in the latest version

import { Token, FixedPointNumber, getPresetToken } from '@acala-network/sdk-core';
import { SwapTrade } from '@acala-network/sdk-swap';

Is there any alternative to that

Editor's config files in repository

Hi ! First, thanks for all the job done, Acala is amazing and having tools like acala.js really helps.

This is not really an issue and as I'm really noob in dev I know my mind about how this repo is managed my opinion doesn't count for much but I thought having editor's config/backup files in a repository wasn't a good thing. So I'm a bit confused seeing .vscode here.

I forked, did a new branch and did two commits (updated .gitignore and resubmit files) so, if you wish, I will be glad to push a PR :)

Thanks !

Token provider returns foreign asset instead of erc20 in case both have same symbol

Hi guys, we found one issue yesterday trying to integrate WETH xcm transfer from acala <-> hydradx. If there are multiple assets with the same symbol, first one is being returned. In our case:

 [
    [
      {
        ForeignAssetId: 6
      }
    ]
    {
      name: Wrapped Ether
      symbol: WETH
      decimals: 18
      minimalBalance: 500,000,000,000,000
   

instead of erc20 token so balance returned by wallet is incorrect.

Would it be possible to either return list of balances covering all the tokens that match token symbol or pass some sort of filter fn in wallet options to handle correct filtering of tokens ?

Here is the line causing the troubles:
https://github.com/AcalaNetwork/acala.js/blob/master/packages/sdk/src/wallet/token-provider/acala.ts#L147

Swap on DeX Issue

Running the wiki example for swapping on Dex I get the follow error:

C:\PROYECTOS\NODE.JS\Acala\swap.js:29
const pool = await api.derive.dex.pool('DOT');
^

TypeError: Cannot read properties of undefined (reading 'pool')
at main (C:\INTOOLGES\PROYECTOS\NODE.JS\Acala\swap.js:29:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Swap on DeX
const { ApiPromise } = require('@polkadot/api');
const { WsProvider } = require('@polkadot/rpc-provider');
const { options } = require('@acala-network/api');
const { Fixed18, convertToFixed18, calcSwapTargetAmount } = require('@acala-network/app-util');

const { Keyring } = require('@polkadot/api');

async function main() {
const provider = new WsProvider('wss://karura.api.onfinality.io/public-ws');
const api = new ApiPromise(options({ provider }));
await api.isReady;

const keyring = new Keyring({ type: 'sr25519' });
const newPair = keyring.addFromUri('yourinput');
const address = newPair.address;
console.log(newPair.address); // you need to get test tokens

// DOT -> aUSD

// Set Supply Amount
const supply = 1

// Query Dex Pool
const pool = await api.derive.dex.pool('DOT');

// Query Exchange Fee
const exchangeFee = api.consts.dex.getExchangeFee;

// Calculate Target Currency Amount
const target = calcSwapTargetAmount(
    supply,
    convertToFixed18(pool.base),
    convertToFixed18(pool.other),
    convertToFixed18(exchangeFee),
    Fixed18.fromNature(0.005)
);

// Exec Exchange
await api.tx.dex.swapCurrency(
    'DOT',
    Fixed18.fromNatural(supply).innerToString(),
    'AUSD',
    Fixed18.fromNatural(target).innerToString()
).signAndSend(newPair);

// Ensure Amount
const dotAccount = await api.query.tokens.accounts(address, 'DOT');
console.log(dotAccount.toHuman());

const aUSDAccount = await api.query.tokens.accounts(address, 'AUSD');
console.log(aUSDAccount.toHuman());

}

main()

How to get asset decimals from the AssetRegistry for all Acala/Karura assets

How can we get asset decimals for all assets with acala.js / polkadot.js programmatically like this ERC20 => asset mapping?
https://github.com/AcalaNetwork/Acala/blob/7a29682ed20b63d21f15328acce68422a181f4f3/modules/asset-registry/src/lib.rs#L765-L785
There are AssetRegistered events of AssetMetadata type in the AssetRegistry module:
https://acala.subscan.io/runtime/AssetRegistry?version=2034
but there are no events in Acala:
https://acala.subscan.io/event?address=&module=assetregistry&event=all&startDate=&endDate=&startBlock=&endBlock=&timeType=date&version=2034
the way there are only some in Karura:
https://karura.subscan.io/event?address=&module=assetregistry&event=all&startDate=&endDate=&startBlock=&endBlock=&timeType=date&version=2040
Neither of them are comprehensive. We do not want to hardcode 10, 12, etc. and wish to cover all the existing cases and new cases as new assets are added to the asset registry.

 {"Token":"BNC"}                             
 {"Token":"KAR"}                             
 {"Token":"KINT"}                            
 {"Token":"KSM"}                             
 {"Token":"KUSD"}                            
 {"Token":"LKSM"}                            
 {"Token":"TAI"}                             
 {"Token":"VSKSM"}                           
 {"Token":"ACA"}                             
 {"Token":"AUSD"}                            
 {"Token":"DOT"}             
 {"ForeignAsset":"0"}                        
 {"ForeignAsset":"1"}                        
 {"ForeignAsset":"2"}                        
 {"StableAssetPoolToken":"0"}                
 {"LiquidCrowdloan":"13"}                    
 [{"Token":"ACA"},{"Token":"AUSD"}]          
 [{"Token":"AUSD"},{"LiquidCrowdloan":"13"}] 
 [{"Token":"DOT"},{"LiquidCrowdloan":"13"}]  
 [{"Token":"KAR"},{"Token":"KSM"}]           
 [{"Token":"KAR"},{"Token":"LKSM"}]          
 [{"Token":"KSM"},{"ForeignAsset":"0"}]      
 [{"Token":"KSM"},{"Token":"LKSM"}]          
 [{"Token":"KUSD"},{"ForeignAsset":"0"}]     
 [{"Token":"KUSD"},{"Token":"BNC"}]          
 [{"Token":"KUSD"},{"Token":"KSM"}]          
 [{"Token":"KUSD"},{"Token":"LKSM"}]         

Unable to connect to local node - Invalid byte where token is required

Hello, im unable to connect to localy run mandala node. im running node using

>cargo run --features "with-karura-runtime with-mandala-runtime" -- --dev --tmp  --ws-external 
    Finished dev [unoptimized + debuginfo] target(s) in 1.32s
     Running `target/debug/acala --dev --tmp --ws-external`
2021-10-24 21:36:17 Running in --dev mode, RPC CORS has been disabled.    
2021-10-24 21:36:17 Acala Node    
2021-10-24 21:36:17 ✌️  version 1.5.1-64331216-x86_64-linux-gnu    
2021-10-24 21:36:17 ❤️  by Acala Developers, 2019-2021    
2021-10-24 21:36:17 📋 Chain specification: Mandala Dev    
2021-10-24 21:36:17 🏷 Node name: silent-shock-3491    
2021-10-24 21:36:17 👤 Role: AUTHORITY    
2021-10-24 21:36:17 💾 Database: RocksDb at /tmp/substratewCeCPS/chains/mandala-dev/db    
2021-10-24 21:36:17 ⛓  Native runtime: mandala-1100 (mandala-0.tx1.au1)    
2021-10-24 21:36:18 🔨 Initializing Genesis block/state (state: 0xb0b9…1d40, header-hash: 0xfa8e…acc5)    
2021-10-24 21:36:28 ⏱  Loaded block-time = 6s from block 0xfa8e0c882da7dd22fa5fdf63bacdff5d782ced2bd63c3e204ea5b5a7ea19acc5    
2021-10-24 21:36:28 Using default protocol ID "sup" because none is configured in the chain specs    
2021-10-24 21:36:28 🏷 Local node identity is: 12D3KooWLyg8yWzTe6YuoemeJePyWGBJZSMbHtMfjNcxGeSkuhmH    
2021-10-24 21:36:28 📦 Highest known block at #0    
2021-10-24 21:36:28 〽️ Prometheus exporter started at 127.0.0.1:9615    
2021-10-24 21:36:28 Listening for new connections on 0.0.0.0:9944.    
2021-10-24 21:36:30 🙌 Starting consensus session on top of parent 0xfa8e0c882da7dd22fa5fdf63bacdff5d782ced2bd63c3e204ea5b5a7ea19acc5    
2021-10-24 21:36:30 🎁 Prepared block for proposing at 1 [hash: 0x9bd29ff20aeff88f5491c5f9c5d0bd4ecf71c90cad5032e92fd6e51bf3b541f7; parent_hash: 0xfa8e…acc5; extrinsics (2): [0x5871…f995, 0xf9bb…809a]]    
2021-10-24 21:36:30 🔖 Pre-sealed block for proposal at 1. Hash now 0x3f3372ba35195f50a1b80f6f6d2002c01dd5eb4cb2da1b5aab47cf937ba31a21, previously 0x9bd29ff20aeff88f5491c5f9c5d0bd4ecf71c90cad5032e92fd6e51bf3b541f7.    
2021-10-24 21:36:30 Possible safety violation: attempted to re-finalize last finalized block 0xfa8e0c882da7dd22fa5fdf63bacdff5d782ced2bd63c3e204ea5b5a7ea19acc5     
2021-10-24 21:36:30 ✨ Imported #1 (0x3f33…1a21)    
2021-10-24 21:36:31 Accepted a new tcp connection from 127.0.0.1:32854.    
2021-10-24 21:36:31 WS Error <Http(Token)>: Invalid byte where token is required.    

i`m trying to connect using simple snippet found in your doc

cat package.json
{
  "name": "mandala",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@acala-network/api": "^3.0.2-4",
    "@polkadot/api": "^6.5.1"
  }
}

index.tx

import { ApiPromise } from '@polkadot/api';
import { WsProvider } from '@polkadot/rpc-provider';
import { options } from '@acala-network/api';

async function main() {
    // const provider = new WsProvider('wss://127.0.0.1:9944');
        const provider = new WsProvider('wss://127.0.0.1:9944');
        const api = new ApiPromise(options({ provider }));
        await api.isReady;

    // use api
}

main()

error

ts-node --log-error --project tsconfig.json index.ts 
2021-10-24 21:40:57          API-WS: disconnected from wss://127.0.0.1:9944: 1006:: connection failed
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<_Event>".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

error from node logs

2021-10-24 21:36:31 Accepted a new tcp connection from 127.0.0.1:32854.    
2021-10-24 21:36:31 WS Error <Http(Token)>: Invalid byte where token is required.    

I have the same problem when running karura chain instead of mandala. Am i missing something ?

Acala DEX SDK returns zero when calling wallet.getPrice('UNQ')

Hi,

When utilizing the Acala DEX SDK, specifically the wallet.getPrice() function, I have encountered an unexpected behavior. For certain token symbols, notably 'UNQ', the function returns zero. This issue appears to be exclusive to some specific tokens, as other tokens do not have this problem.

Best regards,
Michael.

sdk version: 4.1.9-10

`yarn build` is not working

I am able to execute sudo yarn install. But when I execute yarn build, I am getting below error

    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
error TS6053: File '@open-web3/dev-config/config/tsconfig.json' not found.

    at createTSError (/Users/ayushkumarmishra/workspace/acala.js/node_modules/ts-node/src/index.ts:434:12)

Add `collatorSelection` Calls To Type Definitions

As a user of the collatorSelection RPC endpoints, I want to be able to utilize TypeScript's type system while developing against these endpoint.

For example, here is my code:

const currentCandidates = await api.query.collatorSelection.candidates();

I believe that the additional types would need to be added into this file: https://github.com/AcalaNetwork/acala.js/blob/905a7b9691be462e4710b4a8ec08ca698d06f5bb/packages/types/src/interfaces/augment-api-tx.ts

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.