@moonbeam-network/xcm-sdk 1.0.0-dev.21 → 1.0.0-dev.211
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +70 -48
- package/build/index.d.ts +216 -207
- package/build/index.mjs +972 -1
- package/build/index.mjs.map +1 -1
- package/package.json +34 -38
- package/build/index.cjs +0 -2
- package/build/index.cjs.map +0 -1
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,973 @@
|
|
|
1
|
-
import{AssetAmount as G}from"@moonbeam-network/xcm-types";import{convertDecimals as ut}from"@moonbeam-network/xcm-utils";import V from"big.js";import{Contract as nt}from"ethers";import{createPublicClient as at,getContract as rt,http as st}from"viem";function w(a){return"provider"in a}function b(a){return"signer"in a}var k=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];var I=class{address;#t;#e;constructor(t,e){if(!t.address)throw new Error("Contract address is required");this.address=t.address,this.#t=t,this.#e=w(e)?new nt(this.address,k,e):rt({abi:k,address:this.address,publicClient:at({chain:e.chain,transport:st()}),walletClient:e})}async getBalance(){return b(this.#e)?(await this.#e.balanceOf(...this.#t.args)).toBigInt():this.#e.read.balanceOf(this.#t.args)}async getDecimals(){return b(this.#e)?await this.#e.decimals():this.#e.read.decimals()}};import{Contract as ot}from"ethers";import{createPublicClient as z,getContract as ct,http as K}from"viem";var F=[{inputs:[{internalType:"address",name:"currencyAddress",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{components:[{internalType:"uint8",name:"parents",type:"uint8"},{internalType:"bytes[]",name:"interior",type:"bytes[]"}],internalType:"struct Xtokens.Multilocation",name:"destination",type:"tuple"},{internalType:"uint64",name:"weight",type:"uint64"}],name:"transfer",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"currencyAddress",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],internalType:"struct Xtokens.Currency[]",name:"currencies",type:"tuple[]"},{internalType:"uint32",name:"feeItem",type:"uint32"},{components:[{internalType:"uint8",name:"parents",type:"uint8"},{internalType:"bytes[]",name:"interior",type:"bytes[]"}],internalType:"struct Xtokens.Multilocation",name:"destination",type:"tuple"},{internalType:"uint64",name:"weight",type:"uint64"}],name:"transferMultiCurrencies",outputs:[],stateMutability:"nonpayable",type:"function"}];var T=class{address="0x0000000000000000000000000000000000000804";#t;#e;#n;constructor(t,e){this.#t=t,this.#n=e,this.#e=w(e)?new ot(this.address,F,e):ct({abi:F,address:this.address,publicClient:z({chain:e.chain,transport:K()}),walletClient:e})}async transfer(){return b(this.#e)?this.#e[this.#t.func](...this.#t.args):this.#e.write[this.#t.func](this.#t.args)}async getEthersContractEstimatedGas(t){return(await t.estimateGas[this.#t.func](...this.#t.args)).toBigInt()}async getViemContractEstimatedGas(t){return t?t.estimateGas[this.#t.func](this.#t.args):0n}async getFee(t){if(t===0n)return 0n;try{let e=b(this.#e)?await this.getEthersContractEstimatedGas(this.#e):await this.getViemContractEstimatedGas(this.#e),n=await this.getGasPrice();return e*n}catch(e){throw console.error(e),new Error("Can't get a fee. Make sure that you have enough balance!")}}async getGasPrice(){if(w(this.#n)){let{gasPrice:e,maxPriorityFeePerGas:n}=await this.#n.getFeeData();return((e==null?void 0:e.toBigInt())||0n)+((n==null?void 0:n.toBigInt())||0n)}return z({chain:this.#n.chain,transport:K()}).getGasPrice()}};function g(a,t){if(a.module==="Erc20")return new I(a,t);if(a.module==="Xtokens")return new T(a,t);throw new Error(`Contract ${a.module} not found`)}import{CallType as N}from"@moonbeam-network/xcm-builder";import{toBigInt as mt}from"@moonbeam-network/xcm-utils";async function B({address:a,config:t,evmSigner:e,polkadot:n}){let r=t.balance.build({address:a,asset:n.chain.getBalanceAssetId(t.asset)});if(r.type===N.Substrate)return n.query(r);if(!e)throw new Error("Evm signer must be provided");return g(r,e).getBalance()}async function y({address:a,asset:t,config:e,evmSigner:n,polkadot:r}){let s=e.balance.build({address:a,asset:r.chain.getBalanceAssetId(t||e.asset)});if(s.type===N.Substrate)return r.getAssetDecimals(t||e.asset);if(!n)throw new Error("Evm signer must be provided");return g(s,n).getDecimals()}async function D(a,t){if(a.min)return t.query(a.min.build({asset:t.chain.getMinAssetId(a.asset)}));let e=t.chain.getAssetMin(a.asset);if(e){let n=await t.getAssetDecimals(a.asset);return mt(e,n)}return 0n}async function j({transferConfig:a,destinationAddress:t,destinationFee:e,evmSigner:n,polkadot:r,sourceAddress:s}){var O,Q,_,X;let{asset:o,destination:m,source:{chain:c,config:i}}=a,p=G.fromAsset(o,{amount:0n,decimals:await y({address:t,config:i,evmSigner:n,polkadot:r})}),l=(O=i.fee)!=null&&O.asset?G.fromAsset(i.fee.asset,{amount:0n,decimals:await y({address:t,asset:i.fee.asset,config:i,evmSigner:n,polkadot:r})}):p,d=(Q=i.destinationFee)!=null&&Q.asset?G.fromAsset(i.destinationFee.asset,{amount:0n,decimals:await y({address:t,asset:i.destinationFee.asset,config:i,evmSigner:n,polkadot:r})}):p,u=await B({address:s,config:i,evmSigner:n,polkadot:r}),f=await $({address:s,balance:u,feeConfig:i.fee,polkadot:r}),S=i.asset.isEqual(i.destinationFee.asset)?u:await $({address:s,balance:u,feeConfig:i.destinationFee,polkadot:r}),P=await D(i,r),x=(_=i.extrinsic)==null?void 0:_.build({address:t,amount:u,asset:c.getAssetId(o),destination:m.chain,fee:e.amount,feeAsset:c.getAssetId(e),palletInstance:c.getAssetPalletInstance(o),source:c}),v=(X=i.contract)==null?void 0:X.build({address:t,amount:u,asset:c.getAssetId(o),destination:m.chain,fee:e.amount,feeAsset:c.getAssetId(e)}),E=await ft({balance:u,contract:v,decimals:l.decimals,evmSigner:n,extrinsic:x,polkadot:r,sourceAddress:s}),C=p.copyWith({amount:u}),{existentialDeposit:W}=r,R=l.copyWith({amount:E}),Y=l.copyWith({amount:f}),Z=d.copyWith({amount:S}),q=p.copyWith({amount:P}),tt=dt({balanceAmount:C,existentialDeposit:W,feeAmount:R,minAmount:q});return{balance:C,chain:c,destinationFeeBalance:Z,existentialDeposit:W,fee:R,feeBalance:Y,max:tt,min:q}}async function $({address:a,balance:t,feeConfig:e,polkadot:n}){return e?n.query(e.balance.build({address:a,asset:n.chain.getBalanceAssetId(e.asset)})):t}async function ft({balance:a,contract:t,decimals:e,evmSigner:n,extrinsic:r,polkadot:s,sourceAddress:o}){if(t){if(!n)throw new Error("EVM Signer must be provided");return pt(a,t,e,n)}if(r)return lt(a,r,s,o);throw new Error("Either contract or extrinsic must be provided")}async function pt(a,t,e,n){let s=await g(t,n).getFee(a);return ut(s,18,e)}async function lt(a,t,e,n){try{return await e.getFee(n,t)}catch(r){if(a)throw r;return 0n}}function dt({balanceAmount:a,existentialDeposit:t,feeAmount:e,minAmount:n}){let r=a.toBig().minus(n.toBig()).minus(a.isSame(t)?t.toBig():V(0)).minus(a.isSame(e)?e.toBig():V(0));return a.copyWith({amount:r.lt(0)?0n:BigInt(r.toFixed())})}import{ConfigBuilder as U,ConfigService as It}from"@moonbeam-network/xcm-config";import{convertDecimals as xt,toBigInt as J}from"@moonbeam-network/xcm-utils";import A from"big.js";import"@polkadot/api-augment";import{darwiniaPangoro as gt,eq as yt,equilibrium as ht,equilibriumAlphanet as Ct,paring as bt}from"@moonbeam-network/xcm-config";import{AssetAmount as At}from"@moonbeam-network/xcm-types";import{getPolkadotApi as wt}from"@moonbeam-network/xcm-utils";var h=class{api;chain;configService;constructor(t,e,n){this.api=t,this.chain=e,this.configService=n}static async create(t,e){return new h(await wt(t.ws),t,e)}static async createMulti(t,e){return Promise.all(t.map(n=>h.create(n,e)))}get decimals(){return this.api.registry.chainDecimals.at(0)||12}get asset(){let t=this.api.registry.chainTokens.at(0),e=t==null?void 0:t.toString().toLowerCase();if(e==="token"&&[Ct.key,ht.key].includes(this.chain.key))return yt;if(e==="oring"&&this.chain.key===gt.key)return bt;if(!e)throw new Error("No native symbol key found");let n=this.configService.getAsset(e);if(!n)throw new Error(`No asset found for key "${e}" and symbol "${t}"`);return n}get existentialDeposit(){var r,s;let t=(r=this.api.consts.balances)==null?void 0:r.existentialDeposit,e=(s=this.api.consts.eqBalances)==null?void 0:s.existentialDeposit,n=(t==null?void 0:t.toBigInt())||(e==null?void 0:e.toBigInt())||0n;return At.fromAsset(this.asset,{amount:n,decimals:this.decimals})}async getAssetMeta(t){var s,o,m,c,i;let e=((s=this.api.query.assets)==null?void 0:s.metadata)||((o=this.api.query.assetRegistry)==null?void 0:o.metadata)||((m=this.api.query.assetRegistry)==null?void 0:m.currencyMetadatas)||((c=this.api.query.assetRegistry)==null?void 0:c.assetMetadatas)||((i=this.api.query.assetRegistry)==null?void 0:i.assetMetadataMap);if(!e)return;let n=await e(t),r="unwrapOrDefault"in n?n.unwrapOrDefault():n;return{decimals:r.decimals.toNumber(),symbol:r.symbol.toString()}}async getAssetDecimalsFromQuery(t){var r;let e=(r=this.api.query.assetsRegistry)==null?void 0:r.assetDecimals;return e?(await e(t)).unwrapOrDefault().toNumber():void 0}async getAssetDecimals(t){var n;let e=this.chain.getMetadataAssetId(t);return await this.getAssetDecimalsFromQuery(e)||((n=await this.getAssetMeta(e))==null?void 0:n.decimals)||this.chain.getAssetDecimals(t)||this.decimals}async query(t){let e=await this.api.query[t.module][t.func](...t.args);return t.transform(e)}async getFee(t,e){let n=this.api.tx[e.module][e.func],r=e.getArgs(n);return(await n(...r).paymentInfo(t,{nonce:-1})).partialFee.toBigInt()}async transfer(t,e,n){let r=this.api.tx[e.module][e.func],s=e.getArgs(r);return(await r(...s).signAndSend(this.#t(n)?t:n,{nonce:-1,signer:this.#t(n)?n:void 0})).toString()}#t(t){return"signPayload"in t}};import{AssetAmount as L}from"@moonbeam-network/xcm-types";import{toBigInt as St}from"@moonbeam-network/xcm-utils";async function H({transferConfig:a,destinationAddress:t,evmSigner:e,polkadot:n}){let{asset:r,destination:{chain:s,config:o}}=a,m=L.fromAsset(r,{amount:0n,decimals:await y({address:t,config:o,evmSigner:e,polkadot:n})}),c=await B({address:t,config:o,evmSigner:e,polkadot:n}),i=await D(o,n),p=m.copyWith({amount:c}),{existentialDeposit:l}=n,d=await Pt({address:t,config:a,evmSigner:e,polkadot:n}),u=m.copyWith({amount:i});return{balance:p,chain:s,existentialDeposit:l,fee:d,min:u}}async function Pt({address:a,config:t,evmSigner:e,polkadot:n}){let{amount:r,asset:s}=t.source.config.destinationFee,o=await y({address:a,asset:s,config:t.destination.config,evmSigner:e,polkadot:n}),m=L.fromAsset(s,{amount:0n,decimals:o});if(Number.isFinite(r))return m.copyWith({amount:St(r,o)});let c=r.build({api:n.api,asset:n.chain.getAssetId(s)});return m.copyWith({amount:await c.call()})}async function M({configService:a,destinationAddress:t,evmSigner:e,polkadotSigner:n,sourceAddress:r,transferConfig:s}){let[o,m]=await h.createMulti([s.destination.chain,s.source.chain],a),c=await H({destinationAddress:t,evmSigner:e,polkadot:o,transferConfig:s}),i=await Et(m,c.fee),p=await j({destinationAddress:t,destinationFee:i,evmSigner:e,polkadot:m,sourceAddress:r,transferConfig:s});return{destination:c,getEstimate(l){let u=A(J(l,p.balance.decimals).toString()).minus(p.balance.isSame(i)?i.toBig():A(0));return p.balance.copyWith({amount:u.lt(0)?0n:BigInt(u.toFixed())})},isSwapPossible:!0,max:p.max,min:vt(c),source:p,async swap(){return M({configService:a,destinationAddress:r,evmSigner:e,polkadotSigner:n,sourceAddress:t,transferConfig:{...s,destination:s.source,source:s.destination}})},async transfer(l){var v,E;let d=J(l,p.balance.decimals),{asset:u,source:{chain:f,config:S}}=s,P=(v=S.contract)==null?void 0:v.build({address:t,amount:d,asset:f.getAssetId(u),destination:c.chain,fee:i.amount,feeAsset:f.getAssetId(i)}),x=(E=S.extrinsic)==null?void 0:E.build({address:t,amount:d,asset:f.getAssetId(u),destination:c.chain,fee:i.amount,feeAsset:f.getAssetId(i),palletInstance:f.getAssetPalletInstance(u),source:f});if(P){if(!e)throw new Error("EVM Signer must be provided");return g(P,e).transfer().then(C=>typeof C=="object"?C.hash:C)}if(x){if(!n)throw new Error("Polkadot signer must be provided");return m.transfer(r,x,n)}throw new Error("Either contract or extrinsic must be provided")}}}function vt({balance:a,existentialDeposit:t,fee:e,min:n}){let r=A(0).plus(a.isSame(e)?e.toBig():A(0)).plus(a.isSame(t)&&a.toBig().lt(t.toBig())?t.toBig():A(0)).plus(a.toBig().lt(n.toBig())?n.toBig():A(0));return a.copyWith({amount:BigInt(r.toFixed())})}async function Et(a,t){let e=await a.getAssetDecimals(t);return t.decimals===e?t:t.copyWith({amount:xt(t.amount,t.decimals,e),decimals:e})}function $e(a){let t=(a==null?void 0:a.configService)??new It;return{assets(e){let{assets:n,asset:r}=U(t).assets(e);return{assets:n,asset(s){let{sourceChains:o,source:m}=r(s);return{sourceChains:o,source(c){let{destinationChains:i,destination:p}=m(c);return{destinationChains:i,destination(l){return{async accounts(d,u,f){return M({...a,configService:t,destinationAddress:u,evmSigner:(f==null?void 0:f.evmSigner)??(f==null?void 0:f.ethersSigner),sourceAddress:d,transferConfig:p(l).build(),polkadotSigner:f==null?void 0:f.polkadotSigner})}}}}}}}}},async getTransferData({destinationAddress:e,destinationKeyOrChain:n,ethersSigner:r,evmSigner:s,keyOrAsset:o,polkadotSigner:m,sourceAddress:c,sourceKeyOrChain:i}){return M({configService:t,destinationAddress:e,evmSigner:s??r,polkadotSigner:m,sourceAddress:c,transferConfig:U(t).assets().asset(o).source(i).destination(n).build()})}}}export{$e as Sdk,pt as getContractFee,lt as getExtrinsicFee,ft as getFee,$ as getFeeBalances,dt as getMax,j as getSourceData};
|
|
1
|
+
// src/getTransferData/getDestinationData.ts
|
|
2
|
+
import { Parachain as Parachain2 } from "@moonbeam-network/xcm-types";
|
|
3
|
+
import { getSovereignAccountAddresses } from "@moonbeam-network/xcm-utils";
|
|
4
|
+
|
|
5
|
+
// src/getTransferData/getTransferData.utils.ts
|
|
6
|
+
import {
|
|
7
|
+
ContractConfig,
|
|
8
|
+
EvmQueryConfig,
|
|
9
|
+
SubstrateQueryConfig
|
|
10
|
+
} from "@moonbeam-network/xcm-builder";
|
|
11
|
+
import {
|
|
12
|
+
AssetAmount as AssetAmount2,
|
|
13
|
+
EvmChain,
|
|
14
|
+
EvmParachain,
|
|
15
|
+
Parachain
|
|
16
|
+
} from "@moonbeam-network/xcm-types";
|
|
17
|
+
import { convertDecimals, toBigInt } from "@moonbeam-network/xcm-utils";
|
|
18
|
+
import Big from "big.js";
|
|
19
|
+
|
|
20
|
+
// src/services/evm/EvmService.ts
|
|
21
|
+
import {
|
|
22
|
+
createPublicClient,
|
|
23
|
+
http
|
|
24
|
+
} from "viem";
|
|
25
|
+
var EvmService = class _EvmService {
|
|
26
|
+
chain;
|
|
27
|
+
client;
|
|
28
|
+
static create(chain) {
|
|
29
|
+
return new _EvmService(chain);
|
|
30
|
+
}
|
|
31
|
+
constructor(chain) {
|
|
32
|
+
this.chain = chain;
|
|
33
|
+
this.client = createPublicClient({
|
|
34
|
+
chain: chain.getViemChain(),
|
|
35
|
+
transport: http()
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
async query(query) {
|
|
39
|
+
return this.client[query.func](...query.args);
|
|
40
|
+
}
|
|
41
|
+
async getFee(address, contract) {
|
|
42
|
+
const gas = await this.client.estimateContractGas({
|
|
43
|
+
abi: contract.abi,
|
|
44
|
+
account: address,
|
|
45
|
+
address: contract.address,
|
|
46
|
+
args: contract.args,
|
|
47
|
+
functionName: contract.func
|
|
48
|
+
});
|
|
49
|
+
const gasPrice = await this.client.getGasPrice();
|
|
50
|
+
return gas * gasPrice;
|
|
51
|
+
}
|
|
52
|
+
async getBalance(address, contract) {
|
|
53
|
+
const balance = await this.client.readContract({
|
|
54
|
+
abi: contract.abi,
|
|
55
|
+
address: contract.address,
|
|
56
|
+
args: [address],
|
|
57
|
+
functionName: "balanceOf"
|
|
58
|
+
});
|
|
59
|
+
if (typeof balance !== "bigint") {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Could not get balance on ${this.chain.name} for ${address} from contract ${contract.address}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return balance;
|
|
65
|
+
}
|
|
66
|
+
async transfer(signer, contract) {
|
|
67
|
+
const { request } = await this.client.simulateContract({
|
|
68
|
+
abi: contract.abi,
|
|
69
|
+
account: signer.account,
|
|
70
|
+
address: contract.address,
|
|
71
|
+
args: contract.args,
|
|
72
|
+
functionName: contract.func
|
|
73
|
+
});
|
|
74
|
+
const hash = await signer.writeContract(request);
|
|
75
|
+
return hash;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// src/services/polkadot/PolkadotService.ts
|
|
80
|
+
import "@polkadot/api-augment";
|
|
81
|
+
import { AssetAmount } from "@moonbeam-network/xcm-types";
|
|
82
|
+
import { getPolkadotApi } from "@moonbeam-network/xcm-utils";
|
|
83
|
+
var PolkadotService = class _PolkadotService {
|
|
84
|
+
api;
|
|
85
|
+
chain;
|
|
86
|
+
constructor(api, chain) {
|
|
87
|
+
this.api = api;
|
|
88
|
+
this.chain = chain;
|
|
89
|
+
}
|
|
90
|
+
static async create(chain) {
|
|
91
|
+
return new _PolkadotService(await getPolkadotApi(chain.ws), chain);
|
|
92
|
+
}
|
|
93
|
+
static async createMulti(chains) {
|
|
94
|
+
return Promise.all(
|
|
95
|
+
chains.map((chain) => _PolkadotService.create(chain))
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
get decimals() {
|
|
99
|
+
return this.api.registry.chainDecimals.at(0) || 12;
|
|
100
|
+
}
|
|
101
|
+
get existentialDeposit() {
|
|
102
|
+
const existentialDeposit = this.api.consts.balances?.existentialDeposit;
|
|
103
|
+
const eqExistentialDeposit = this.api.consts.eqBalances?.existentialDeposit;
|
|
104
|
+
const amount = existentialDeposit?.toBigInt() || eqExistentialDeposit?.toBigInt() || 0n;
|
|
105
|
+
return AssetAmount.fromChainAsset(this.chain.nativeAsset, { amount });
|
|
106
|
+
}
|
|
107
|
+
async query(config) {
|
|
108
|
+
const response = await this.api.query[config.module][config.func](
|
|
109
|
+
...config.args
|
|
110
|
+
);
|
|
111
|
+
return config.transform(response);
|
|
112
|
+
}
|
|
113
|
+
getExtrinsic(config) {
|
|
114
|
+
const fn = this.api.tx[config.module][config.func];
|
|
115
|
+
const args = config.getArgs(fn);
|
|
116
|
+
return fn(...args);
|
|
117
|
+
}
|
|
118
|
+
getExtrinsicCallHash(config) {
|
|
119
|
+
return this.getExtrinsic(config).method.toHex();
|
|
120
|
+
}
|
|
121
|
+
async getPaymentInfo(account, config) {
|
|
122
|
+
const extrinsic = this.getExtrinsic(config);
|
|
123
|
+
return extrinsic.paymentInfo(account, { nonce: -1 });
|
|
124
|
+
}
|
|
125
|
+
async getFee(account, config) {
|
|
126
|
+
const info = await this.getPaymentInfo(account, config);
|
|
127
|
+
return info.partialFee.toBigInt();
|
|
128
|
+
}
|
|
129
|
+
async transfer(account, config, signer, statusCallback) {
|
|
130
|
+
const extrinsic = this.getExtrinsic(config);
|
|
131
|
+
const isSigner = this.#isSigner(signer);
|
|
132
|
+
const signOptions = {
|
|
133
|
+
nonce: -1,
|
|
134
|
+
signer: isSigner ? signer : void 0,
|
|
135
|
+
withSignedTransaction: true
|
|
136
|
+
};
|
|
137
|
+
const hash = await new Promise((resolve, reject) => {
|
|
138
|
+
extrinsic.signAndSend(isSigner ? account : signer, signOptions, (result) => {
|
|
139
|
+
if (result.isError || result.dispatchError) {
|
|
140
|
+
reject(
|
|
141
|
+
new Error(
|
|
142
|
+
result.dispatchError?.toString() || "Transaction failed"
|
|
143
|
+
)
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
if (result.txHash) {
|
|
147
|
+
resolve(result.txHash.toString());
|
|
148
|
+
}
|
|
149
|
+
statusCallback?.(result);
|
|
150
|
+
}).catch(reject);
|
|
151
|
+
});
|
|
152
|
+
return hash;
|
|
153
|
+
}
|
|
154
|
+
#isSigner(signer) {
|
|
155
|
+
return "signPayload" in signer;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// src/getTransferData/getTransferData.utils.ts
|
|
160
|
+
async function getBalance({
|
|
161
|
+
address,
|
|
162
|
+
asset,
|
|
163
|
+
builder,
|
|
164
|
+
chain
|
|
165
|
+
}) {
|
|
166
|
+
const config = builder.build({
|
|
167
|
+
address,
|
|
168
|
+
asset
|
|
169
|
+
});
|
|
170
|
+
const amount = AssetAmount2.fromChainAsset(asset, { amount: 0n });
|
|
171
|
+
if (SubstrateQueryConfig.is(config) && EvmParachain.isAnyParachain(chain)) {
|
|
172
|
+
const polkadot = await PolkadotService.create(chain);
|
|
173
|
+
const balance = await polkadot.query(config);
|
|
174
|
+
const converted = chain.usesChainDecimals ? convertDecimals(balance, polkadot.decimals, asset.decimals) : balance;
|
|
175
|
+
return amount.copyWith({ amount: converted });
|
|
176
|
+
}
|
|
177
|
+
if (EvmChain.is(chain) || EvmParachain.is(chain)) {
|
|
178
|
+
const evm = EvmService.create(chain);
|
|
179
|
+
if (ContractConfig.is(config)) {
|
|
180
|
+
const balance = await evm.getBalance(address, config);
|
|
181
|
+
return amount.copyWith({ amount: balance });
|
|
182
|
+
}
|
|
183
|
+
if (EvmQueryConfig.is(config)) {
|
|
184
|
+
const balance = await evm.query(config);
|
|
185
|
+
return amount.copyWith({ amount: balance });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
throw new Error(
|
|
189
|
+
`Can't get balance for ${address} on chain ${chain.name} and asset ${asset.symbol}`
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
async function getAssetMin({
|
|
193
|
+
asset,
|
|
194
|
+
builder,
|
|
195
|
+
chain
|
|
196
|
+
}) {
|
|
197
|
+
const zero = AssetAmount2.fromChainAsset(chain.getChainAsset(asset), {
|
|
198
|
+
amount: 0n
|
|
199
|
+
});
|
|
200
|
+
if (builder && EvmParachain.isAnyParachain(chain)) {
|
|
201
|
+
const polkadot = await PolkadotService.create(chain);
|
|
202
|
+
const min = await polkadot.query(
|
|
203
|
+
builder.build({ asset: zero.getMinAssetId(), address: zero.address })
|
|
204
|
+
);
|
|
205
|
+
return zero.copyWith({ amount: min });
|
|
206
|
+
}
|
|
207
|
+
if (zero.min) {
|
|
208
|
+
return zero.copyWith({ amount: zero.min });
|
|
209
|
+
}
|
|
210
|
+
return zero;
|
|
211
|
+
}
|
|
212
|
+
function getMin({
|
|
213
|
+
balance,
|
|
214
|
+
existentialDeposit,
|
|
215
|
+
fee,
|
|
216
|
+
min
|
|
217
|
+
}) {
|
|
218
|
+
const result = Big(0).plus(balance.isSame(fee) ? fee.toBig() : Big(0)).plus(
|
|
219
|
+
existentialDeposit && balance.isSame(existentialDeposit) && balance.toBig().lt(existentialDeposit.toBig()) ? existentialDeposit.toBig() : Big(0)
|
|
220
|
+
).plus(balance.toBig().lt(min.toBig()) ? min.toBig() : Big(0));
|
|
221
|
+
return balance.copyWith({
|
|
222
|
+
amount: BigInt(result.toFixed())
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
function getMax({
|
|
226
|
+
balance,
|
|
227
|
+
existentialDeposit,
|
|
228
|
+
fee,
|
|
229
|
+
min
|
|
230
|
+
}) {
|
|
231
|
+
const result = balance.toBig().minus(min.toBig()).minus(
|
|
232
|
+
existentialDeposit && balance.isSame(existentialDeposit) ? existentialDeposit.toBig() : Big(0)
|
|
233
|
+
).minus(balance.isSame(fee) ? fee.toBig() : Big(0));
|
|
234
|
+
return balance.copyWith({
|
|
235
|
+
amount: result.lt(0) ? 0n : BigInt(result.toFixed())
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async function getDestinationFee({
|
|
239
|
+
address,
|
|
240
|
+
asset,
|
|
241
|
+
destination,
|
|
242
|
+
fee,
|
|
243
|
+
feeAsset,
|
|
244
|
+
source
|
|
245
|
+
}) {
|
|
246
|
+
const zero = AssetAmount2.fromChainAsset(destination.getChainAsset(feeAsset), {
|
|
247
|
+
amount: 0n
|
|
248
|
+
});
|
|
249
|
+
if (typeof fee === "number") {
|
|
250
|
+
return zero.copyWith({
|
|
251
|
+
amount: fee
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
if (EvmParachain.isAnyParachain(destination)) {
|
|
255
|
+
const polkadot = await PolkadotService.create(destination);
|
|
256
|
+
const cfg = fee.build({
|
|
257
|
+
address,
|
|
258
|
+
api: polkadot.api,
|
|
259
|
+
asset: destination.getChainAsset(asset),
|
|
260
|
+
destination,
|
|
261
|
+
feeAsset: destination.getChainAsset(feeAsset),
|
|
262
|
+
source
|
|
263
|
+
});
|
|
264
|
+
return zero.copyWith({
|
|
265
|
+
amount: await cfg.call()
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return zero;
|
|
269
|
+
}
|
|
270
|
+
function convertToChainDecimals({
|
|
271
|
+
asset,
|
|
272
|
+
target
|
|
273
|
+
}) {
|
|
274
|
+
return AssetAmount2.fromChainAsset(target, {
|
|
275
|
+
amount: asset.convertDecimals(target.decimals).amount
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
async function getExistentialDeposit(chain) {
|
|
279
|
+
if (EvmParachain.isAnyParachain(chain)) {
|
|
280
|
+
const polkadot = await PolkadotService.create(chain);
|
|
281
|
+
return polkadot.existentialDeposit;
|
|
282
|
+
}
|
|
283
|
+
return void 0;
|
|
284
|
+
}
|
|
285
|
+
async function getDestinationFeeBalance({
|
|
286
|
+
balance,
|
|
287
|
+
feeBalance,
|
|
288
|
+
route,
|
|
289
|
+
sourceAddress
|
|
290
|
+
}) {
|
|
291
|
+
if (route.destination.fee.asset.isEqual(balance)) {
|
|
292
|
+
return balance;
|
|
293
|
+
}
|
|
294
|
+
if (route.destination.fee.asset.isEqual(feeBalance)) {
|
|
295
|
+
return feeBalance;
|
|
296
|
+
}
|
|
297
|
+
if (!route.source.destinationFee?.balance) {
|
|
298
|
+
throw new Error(
|
|
299
|
+
"BalanceBuilder must be defined for source.destinationFee.balance for AssetRoute"
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
return getBalance({
|
|
303
|
+
address: sourceAddress,
|
|
304
|
+
asset: route.getDestinationFeeAssetOnSource(),
|
|
305
|
+
builder: route.source.destinationFee?.balance,
|
|
306
|
+
chain: route.source.chain
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
async function getExtrinsicFee({
|
|
310
|
+
address,
|
|
311
|
+
balance,
|
|
312
|
+
chain,
|
|
313
|
+
extrinsic,
|
|
314
|
+
feeBalance,
|
|
315
|
+
feeConfig
|
|
316
|
+
}) {
|
|
317
|
+
try {
|
|
318
|
+
const polkadot = await PolkadotService.create(chain);
|
|
319
|
+
const fee = await polkadot.getFee(address, extrinsic);
|
|
320
|
+
const extra = feeConfig?.extra ? toBigInt(feeConfig.extra, feeBalance.decimals) : 0n;
|
|
321
|
+
const totalFee = fee + extra;
|
|
322
|
+
const converted = chain.usesChainDecimals ? convertDecimals(totalFee, polkadot.decimals, feeBalance.decimals) : totalFee;
|
|
323
|
+
return feeBalance.copyWith({ amount: converted });
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (balance.amount) {
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
return feeBalance.copyWith({ amount: 0n });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async function getContractFee({
|
|
332
|
+
address,
|
|
333
|
+
balance,
|
|
334
|
+
chain,
|
|
335
|
+
contract,
|
|
336
|
+
destinationFee,
|
|
337
|
+
feeBalance,
|
|
338
|
+
feeConfig
|
|
339
|
+
}) {
|
|
340
|
+
try {
|
|
341
|
+
if (balance.amount === 0n) {
|
|
342
|
+
return feeBalance.copyWith({ amount: 0n });
|
|
343
|
+
}
|
|
344
|
+
const evm = EvmService.create(chain);
|
|
345
|
+
const fee = await evm.getFee(address, contract);
|
|
346
|
+
const extra = feeConfig?.extra ? toBigInt(feeConfig.extra, feeBalance.decimals) : 0n;
|
|
347
|
+
return feeBalance.copyWith({ amount: fee + extra });
|
|
348
|
+
} catch (error) {
|
|
349
|
+
throw new Error(
|
|
350
|
+
`Can't get a fee, make sure you have ${destinationFee.toDecimal()} ${destinationFee.getSymbol()} in your source balance, needed for destination fees`,
|
|
351
|
+
{ cause: error }
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
function validateSovereignAccountBalances({
|
|
356
|
+
amount,
|
|
357
|
+
sourceData,
|
|
358
|
+
destinationData
|
|
359
|
+
}) {
|
|
360
|
+
if (!Parachain.is(destinationData.chain) || !destinationData.chain.checkSovereignAccountBalances || !destinationData.sovereignAccountBalances) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const { feeAssetBalance, transferAssetBalance } = destinationData.sovereignAccountBalances;
|
|
364
|
+
if (amount > transferAssetBalance) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
`${sourceData.chain.name} Sovereign account in ${destinationData.chain.name} does not have enough balance for this transaction`
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
if (feeAssetBalance && sourceData.destinationFee.amount > feeAssetBalance) {
|
|
370
|
+
throw new Error(
|
|
371
|
+
`${sourceData.chain.name} Sovereign account in ${destinationData.chain.name} does not have enough balance to pay for fees for this transaction`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// src/getTransferData/getDestinationData.ts
|
|
377
|
+
async function getDestinationData({
|
|
378
|
+
route,
|
|
379
|
+
destinationAddress
|
|
380
|
+
}) {
|
|
381
|
+
const destination = route.destination.chain;
|
|
382
|
+
const asset = destination.getChainAsset(route.destination.asset);
|
|
383
|
+
const balance = await getBalance({
|
|
384
|
+
address: destinationAddress,
|
|
385
|
+
asset,
|
|
386
|
+
builder: route.destination.balance,
|
|
387
|
+
chain: destination
|
|
388
|
+
});
|
|
389
|
+
const min = await getAssetMin({
|
|
390
|
+
asset,
|
|
391
|
+
builder: route.destination.min,
|
|
392
|
+
chain: destination
|
|
393
|
+
});
|
|
394
|
+
const fee = await getDestinationFee({
|
|
395
|
+
address: destinationAddress,
|
|
396
|
+
feeAsset: route.destination.fee.asset,
|
|
397
|
+
destination,
|
|
398
|
+
fee: route.destination.fee.amount,
|
|
399
|
+
source: route.source.chain,
|
|
400
|
+
asset: route.source.asset
|
|
401
|
+
});
|
|
402
|
+
const existentialDeposit = await getExistentialDeposit(destination);
|
|
403
|
+
return {
|
|
404
|
+
chain: destination,
|
|
405
|
+
balance,
|
|
406
|
+
existentialDeposit,
|
|
407
|
+
fee,
|
|
408
|
+
min,
|
|
409
|
+
sovereignAccountBalances: await getSovereignAccountBalances({
|
|
410
|
+
source: route.source,
|
|
411
|
+
destination: route.destination
|
|
412
|
+
})
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
async function getSovereignAccountBalances({
|
|
416
|
+
destination,
|
|
417
|
+
source
|
|
418
|
+
}) {
|
|
419
|
+
if (!Parachain2.is(source.chain) || !Parachain2.is(destination.chain) || !destination.chain.checkSovereignAccountBalances) {
|
|
420
|
+
return void 0;
|
|
421
|
+
}
|
|
422
|
+
const sovereignAccountAddresses = getSovereignAccountAddresses(
|
|
423
|
+
source.chain.parachainId
|
|
424
|
+
);
|
|
425
|
+
const destinationFeeAssetBalance = destination.fee.balance;
|
|
426
|
+
const sovereignAccountAddress = destination.chain.isRelay ? sovereignAccountAddresses.relay : sovereignAccountAddresses.generic;
|
|
427
|
+
const sovereignAccountBalance = await getBalance({
|
|
428
|
+
address: sovereignAccountAddress,
|
|
429
|
+
asset: destination.chain.getChainAsset(destination.asset),
|
|
430
|
+
builder: destination.balance,
|
|
431
|
+
chain: destination.chain
|
|
432
|
+
});
|
|
433
|
+
const sovereignAccountFeeAssetBalance = destinationFeeAssetBalance ? await getBalance({
|
|
434
|
+
address: sovereignAccountAddress,
|
|
435
|
+
asset: destination.chain.getChainAsset(destination.fee.asset),
|
|
436
|
+
builder: destinationFeeAssetBalance,
|
|
437
|
+
chain: destination.chain
|
|
438
|
+
}) : void 0;
|
|
439
|
+
return {
|
|
440
|
+
feeAssetBalance: sovereignAccountFeeAssetBalance?.amount,
|
|
441
|
+
transferAssetBalance: sovereignAccountBalance.amount
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// src/getTransferData/getSourceData.ts
|
|
446
|
+
async function getSourceData({
|
|
447
|
+
route,
|
|
448
|
+
destinationAddress,
|
|
449
|
+
destinationFee,
|
|
450
|
+
sourceAddress
|
|
451
|
+
}) {
|
|
452
|
+
const source = route.source.chain;
|
|
453
|
+
const destination = route.destination.chain;
|
|
454
|
+
const [sourcePolkadot, destinationPolkadot] = await PolkadotService.createMulti([source, destination]);
|
|
455
|
+
const asset = source.getChainAsset(route.source.asset);
|
|
456
|
+
const feeAsset = route.source.fee ? source.getChainAsset(route.source.fee.asset) : asset;
|
|
457
|
+
const balance = await getBalance({
|
|
458
|
+
address: sourceAddress,
|
|
459
|
+
asset,
|
|
460
|
+
builder: route.source.balance,
|
|
461
|
+
chain: source
|
|
462
|
+
});
|
|
463
|
+
const feeBalance = await getBalance({
|
|
464
|
+
address: sourceAddress,
|
|
465
|
+
asset: feeAsset,
|
|
466
|
+
builder: route.source.fee.balance,
|
|
467
|
+
chain: source
|
|
468
|
+
});
|
|
469
|
+
const destinationFeeBalance = await getDestinationFeeBalance({
|
|
470
|
+
balance,
|
|
471
|
+
feeBalance,
|
|
472
|
+
route,
|
|
473
|
+
sourceAddress
|
|
474
|
+
});
|
|
475
|
+
const existentialDeposit = await getExistentialDeposit(source);
|
|
476
|
+
const min = await getAssetMin({
|
|
477
|
+
asset,
|
|
478
|
+
builder: route.source.min,
|
|
479
|
+
chain: source
|
|
480
|
+
});
|
|
481
|
+
const extrinsic = route.extrinsic?.build({
|
|
482
|
+
asset: balance,
|
|
483
|
+
destination: route.destination.chain,
|
|
484
|
+
destinationAddress,
|
|
485
|
+
destinationApi: destinationPolkadot.api,
|
|
486
|
+
fee: destinationFee,
|
|
487
|
+
source,
|
|
488
|
+
sourceAddress,
|
|
489
|
+
sourceApi: sourcePolkadot.api
|
|
490
|
+
});
|
|
491
|
+
const contract = route.contract?.build({
|
|
492
|
+
asset: balance,
|
|
493
|
+
destination: route.destination.chain,
|
|
494
|
+
destinationAddress,
|
|
495
|
+
destinationApi: destinationPolkadot.api,
|
|
496
|
+
fee: destinationFee,
|
|
497
|
+
source,
|
|
498
|
+
sourceAddress,
|
|
499
|
+
sourceApi: sourcePolkadot.api
|
|
500
|
+
});
|
|
501
|
+
const fee = await getFee({
|
|
502
|
+
balance,
|
|
503
|
+
chain: source,
|
|
504
|
+
contract,
|
|
505
|
+
destinationFee,
|
|
506
|
+
extrinsic,
|
|
507
|
+
feeBalance,
|
|
508
|
+
feeConfig: route.source.fee,
|
|
509
|
+
sourceAddress
|
|
510
|
+
});
|
|
511
|
+
const max = getMax({
|
|
512
|
+
balance,
|
|
513
|
+
existentialDeposit,
|
|
514
|
+
fee,
|
|
515
|
+
min
|
|
516
|
+
});
|
|
517
|
+
return {
|
|
518
|
+
balance,
|
|
519
|
+
chain: source,
|
|
520
|
+
destinationFee,
|
|
521
|
+
destinationFeeBalance,
|
|
522
|
+
existentialDeposit,
|
|
523
|
+
fee,
|
|
524
|
+
feeBalance,
|
|
525
|
+
max,
|
|
526
|
+
min
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
async function getFee({
|
|
530
|
+
balance,
|
|
531
|
+
feeBalance,
|
|
532
|
+
chain,
|
|
533
|
+
contract,
|
|
534
|
+
destinationFee,
|
|
535
|
+
extrinsic,
|
|
536
|
+
feeConfig,
|
|
537
|
+
sourceAddress
|
|
538
|
+
}) {
|
|
539
|
+
if (!contract && !extrinsic) {
|
|
540
|
+
throw new Error("Either contract or extrinsic must be provided");
|
|
541
|
+
}
|
|
542
|
+
if (contract) {
|
|
543
|
+
return getContractFee({
|
|
544
|
+
address: sourceAddress,
|
|
545
|
+
balance,
|
|
546
|
+
chain,
|
|
547
|
+
contract,
|
|
548
|
+
destinationFee,
|
|
549
|
+
feeBalance,
|
|
550
|
+
feeConfig
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
return getExtrinsicFee({
|
|
554
|
+
address: sourceAddress,
|
|
555
|
+
balance,
|
|
556
|
+
chain,
|
|
557
|
+
extrinsic,
|
|
558
|
+
feeBalance,
|
|
559
|
+
feeConfig
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
async function getAssetsBalances({
|
|
563
|
+
address,
|
|
564
|
+
chain,
|
|
565
|
+
routes
|
|
566
|
+
}) {
|
|
567
|
+
const uniqueRoutes = routes.reduce((acc, route) => {
|
|
568
|
+
if (!acc.some((a) => a.source.asset.isEqual(route.source.asset))) {
|
|
569
|
+
return [route, ...acc];
|
|
570
|
+
}
|
|
571
|
+
return acc;
|
|
572
|
+
}, []);
|
|
573
|
+
const balances = await Promise.all(
|
|
574
|
+
uniqueRoutes.map(
|
|
575
|
+
async (route) => getBalance({
|
|
576
|
+
address,
|
|
577
|
+
asset: chain.getChainAsset(route.source.asset),
|
|
578
|
+
builder: route.source.balance,
|
|
579
|
+
chain
|
|
580
|
+
})
|
|
581
|
+
)
|
|
582
|
+
);
|
|
583
|
+
return balances;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// src/sdk.ts
|
|
587
|
+
import { ConfigService, xcmRoutesMap } from "@moonbeam-network/xcm-config";
|
|
588
|
+
import {
|
|
589
|
+
EvmParachain as EvmParachain2
|
|
590
|
+
} from "@moonbeam-network/xcm-types";
|
|
591
|
+
|
|
592
|
+
// src/getTransferData/getTransferData.ts
|
|
593
|
+
import {
|
|
594
|
+
AssetAmount as AssetAmount3
|
|
595
|
+
} from "@moonbeam-network/xcm-types";
|
|
596
|
+
import { toBigInt as toBigInt2 } from "@moonbeam-network/xcm-utils";
|
|
597
|
+
import Big2 from "big.js";
|
|
598
|
+
|
|
599
|
+
// src/utils/monitoring.ts
|
|
600
|
+
import { getPolkadotApi as getPolkadotApi2 } from "@moonbeam-network/xcm-utils";
|
|
601
|
+
async function listenToDestinationEvents({
|
|
602
|
+
route,
|
|
603
|
+
messageId,
|
|
604
|
+
onDestinationFinalized,
|
|
605
|
+
onDestinationError
|
|
606
|
+
}) {
|
|
607
|
+
if (!route?.destination?.chain || !("ws" in route.destination.chain)) {
|
|
608
|
+
console.log("No destination WS endpoint available");
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
try {
|
|
612
|
+
const monitoringConfig = route?.monitoring;
|
|
613
|
+
if (!monitoringConfig) {
|
|
614
|
+
console.log("No monitoring config found");
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
const api = await getPolkadotApi2(route.destination.chain.ws);
|
|
618
|
+
console.log("Subscribing to destination events...");
|
|
619
|
+
const unsubscribe = await api.query.system.events((events) => {
|
|
620
|
+
console.log("Destination events:", events.toHuman());
|
|
621
|
+
const destinationResult = monitoringConfig.checkDestination(
|
|
622
|
+
events,
|
|
623
|
+
messageId
|
|
624
|
+
);
|
|
625
|
+
if (destinationResult.matched) {
|
|
626
|
+
console.log(
|
|
627
|
+
"Destination event matched:",
|
|
628
|
+
destinationResult.event?.toHuman()
|
|
629
|
+
);
|
|
630
|
+
unsubscribe();
|
|
631
|
+
if (destinationResult.success) {
|
|
632
|
+
onDestinationFinalized?.();
|
|
633
|
+
} else {
|
|
634
|
+
const error = new Error(
|
|
635
|
+
`Message processing failed on destination chain: ${route.destination.chain.name}`
|
|
636
|
+
);
|
|
637
|
+
console.error(
|
|
638
|
+
"Destination message processing failed:",
|
|
639
|
+
destinationResult.event?.toHuman()
|
|
640
|
+
);
|
|
641
|
+
onDestinationError?.(error);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
} catch (error) {
|
|
646
|
+
console.error("Error listening to destination events:", error);
|
|
647
|
+
onDestinationError?.(error);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
function processSourceEvents({
|
|
651
|
+
events,
|
|
652
|
+
sourceAddress,
|
|
653
|
+
route,
|
|
654
|
+
onSourceFinalized,
|
|
655
|
+
onSourceError,
|
|
656
|
+
onDestinationFinalized,
|
|
657
|
+
onDestinationError,
|
|
658
|
+
unsubscribe
|
|
659
|
+
}) {
|
|
660
|
+
const extrinsicFailedEvent = events.find((event) => {
|
|
661
|
+
return event.event.section === "system" && event.event.method === "ExtrinsicFailed";
|
|
662
|
+
});
|
|
663
|
+
if (extrinsicFailedEvent) {
|
|
664
|
+
onSourceError?.(new Error("Extrinsic failed"));
|
|
665
|
+
unsubscribe?.();
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
const monitoringConfig = route.monitoring;
|
|
669
|
+
if (!monitoringConfig) {
|
|
670
|
+
console.log("No valid MonitoringBuilder config found");
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
console.log("Using MonitoringBuilder config");
|
|
674
|
+
try {
|
|
675
|
+
const sourceResult = monitoringConfig.checkSource(events, sourceAddress);
|
|
676
|
+
if (sourceResult.matched) {
|
|
677
|
+
console.log("Source event matched:", sourceResult.event?.toHuman());
|
|
678
|
+
onSourceFinalized?.();
|
|
679
|
+
if (unsubscribe) {
|
|
680
|
+
console.log("Unsubscribing from source events...");
|
|
681
|
+
unsubscribe();
|
|
682
|
+
}
|
|
683
|
+
listenToDestinationEvents({
|
|
684
|
+
route,
|
|
685
|
+
messageId: sourceResult.messageId,
|
|
686
|
+
onDestinationFinalized,
|
|
687
|
+
onDestinationError
|
|
688
|
+
});
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
} catch (error) {
|
|
692
|
+
console.error("Error in MonitoringBuilder config:", error);
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
console.log("No monitoring events matched");
|
|
696
|
+
}
|
|
697
|
+
function createMonitoringCallback({
|
|
698
|
+
sourceAddress,
|
|
699
|
+
route,
|
|
700
|
+
extrinsic,
|
|
701
|
+
statusCallback,
|
|
702
|
+
onSourceFinalized,
|
|
703
|
+
onSourceError,
|
|
704
|
+
onDestinationFinalized,
|
|
705
|
+
onDestinationError
|
|
706
|
+
}) {
|
|
707
|
+
return (status) => {
|
|
708
|
+
statusCallback?.(status);
|
|
709
|
+
console.log("status", status.toHuman());
|
|
710
|
+
const extrinsicPalletName = extrinsic?.module;
|
|
711
|
+
const extrinsicFunctionName = extrinsic?.func;
|
|
712
|
+
if (extrinsicPalletName && extrinsicFunctionName) {
|
|
713
|
+
console.log(
|
|
714
|
+
`Monitoring extrinsic: ${extrinsicPalletName}::${extrinsicFunctionName}`
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
processSourceEvents({
|
|
718
|
+
events: status.events,
|
|
719
|
+
sourceAddress,
|
|
720
|
+
route,
|
|
721
|
+
extrinsic,
|
|
722
|
+
onSourceFinalized,
|
|
723
|
+
onSourceError,
|
|
724
|
+
onDestinationFinalized,
|
|
725
|
+
onDestinationError
|
|
726
|
+
});
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
async function listenToSourceEvents({
|
|
730
|
+
route,
|
|
731
|
+
sourceAddress,
|
|
732
|
+
onSourceFinalized,
|
|
733
|
+
onSourceError,
|
|
734
|
+
onDestinationFinalized,
|
|
735
|
+
onDestinationError
|
|
736
|
+
}) {
|
|
737
|
+
if (!route?.source?.chain || !("ws" in route.source.chain)) {
|
|
738
|
+
console.log("No source WS endpoint available");
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
try {
|
|
742
|
+
const api = await getPolkadotApi2(route.source.chain.ws);
|
|
743
|
+
console.log("Subscribing to source events...");
|
|
744
|
+
const unsubscribe = await api.query.system.events((events) => {
|
|
745
|
+
console.log("Source events:", events.toHuman());
|
|
746
|
+
processSourceEvents({
|
|
747
|
+
events,
|
|
748
|
+
sourceAddress,
|
|
749
|
+
route,
|
|
750
|
+
onSourceFinalized,
|
|
751
|
+
onSourceError,
|
|
752
|
+
onDestinationFinalized,
|
|
753
|
+
onDestinationError,
|
|
754
|
+
unsubscribe
|
|
755
|
+
});
|
|
756
|
+
});
|
|
757
|
+
} catch (error) {
|
|
758
|
+
console.error("Error listening to source events:", error);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// src/getTransferData/getTransferData.ts
|
|
763
|
+
async function getTransferData({
|
|
764
|
+
route,
|
|
765
|
+
sourceAddress,
|
|
766
|
+
destinationAddress
|
|
767
|
+
}) {
|
|
768
|
+
const destinationData = await getDestinationData({
|
|
769
|
+
route,
|
|
770
|
+
destinationAddress
|
|
771
|
+
});
|
|
772
|
+
const destinationFee = convertToChainDecimals({
|
|
773
|
+
asset: destinationData.fee,
|
|
774
|
+
target: route.getDestinationFeeAssetOnSource()
|
|
775
|
+
});
|
|
776
|
+
const sourceData = await getSourceData({
|
|
777
|
+
route,
|
|
778
|
+
destinationAddress,
|
|
779
|
+
destinationFee,
|
|
780
|
+
sourceAddress
|
|
781
|
+
});
|
|
782
|
+
return {
|
|
783
|
+
destination: destinationData,
|
|
784
|
+
getEstimate(amount) {
|
|
785
|
+
const bigAmount = Big2(
|
|
786
|
+
toBigInt2(amount, sourceData.balance.decimals).toString()
|
|
787
|
+
);
|
|
788
|
+
const result = bigAmount.minus(
|
|
789
|
+
sourceData.balance.isSame(destinationFee) ? destinationFee.toBig() : Big2(0)
|
|
790
|
+
);
|
|
791
|
+
return sourceData.balance.copyWith({
|
|
792
|
+
amount: result.lt(0) ? 0n : BigInt(result.toFixed())
|
|
793
|
+
});
|
|
794
|
+
},
|
|
795
|
+
max: sourceData.max,
|
|
796
|
+
min: getMin(destinationData),
|
|
797
|
+
source: sourceData,
|
|
798
|
+
async transfer({
|
|
799
|
+
amount,
|
|
800
|
+
signers: { evmSigner, polkadotSigner },
|
|
801
|
+
statusCallback,
|
|
802
|
+
onSourceFinalized,
|
|
803
|
+
onSourceError,
|
|
804
|
+
onDestinationFinalized,
|
|
805
|
+
onDestinationError
|
|
806
|
+
}) {
|
|
807
|
+
const source = route.source.chain;
|
|
808
|
+
const destination = route.destination.chain;
|
|
809
|
+
const bigintAmount = toBigInt2(amount, sourceData.balance.decimals);
|
|
810
|
+
validateSovereignAccountBalances({
|
|
811
|
+
amount: bigintAmount,
|
|
812
|
+
destinationData,
|
|
813
|
+
sourceData
|
|
814
|
+
});
|
|
815
|
+
const asset = AssetAmount3.fromChainAsset(
|
|
816
|
+
route.source.chain.getChainAsset(route.source.asset),
|
|
817
|
+
{ amount: bigintAmount }
|
|
818
|
+
);
|
|
819
|
+
const [sourcePolkadot, destinationPolkadot] = await PolkadotService.createMulti([source, destination]);
|
|
820
|
+
const contract = route.contract?.build({
|
|
821
|
+
asset,
|
|
822
|
+
destination,
|
|
823
|
+
destinationAddress,
|
|
824
|
+
destinationApi: destinationPolkadot.api,
|
|
825
|
+
fee: destinationFee,
|
|
826
|
+
source,
|
|
827
|
+
sourceAddress,
|
|
828
|
+
sourceApi: sourcePolkadot.api
|
|
829
|
+
});
|
|
830
|
+
const extrinsic = route.extrinsic?.build({
|
|
831
|
+
asset,
|
|
832
|
+
destination,
|
|
833
|
+
destinationAddress,
|
|
834
|
+
destinationApi: destinationPolkadot.api,
|
|
835
|
+
fee: destinationFee,
|
|
836
|
+
source,
|
|
837
|
+
sourceAddress,
|
|
838
|
+
sourceApi: sourcePolkadot.api
|
|
839
|
+
});
|
|
840
|
+
const shouldListenToEvents = !!onSourceFinalized || !!onSourceError || !!onDestinationFinalized || !!onDestinationError;
|
|
841
|
+
if (contract) {
|
|
842
|
+
if (!evmSigner) {
|
|
843
|
+
throw new Error("EVM Signer must be provided");
|
|
844
|
+
}
|
|
845
|
+
const evm = EvmService.create(source);
|
|
846
|
+
const hash = await evm.transfer(evmSigner, contract);
|
|
847
|
+
if (shouldListenToEvents) {
|
|
848
|
+
listenToSourceEvents({
|
|
849
|
+
route,
|
|
850
|
+
sourceAddress,
|
|
851
|
+
onSourceFinalized,
|
|
852
|
+
onSourceError,
|
|
853
|
+
onDestinationFinalized,
|
|
854
|
+
onDestinationError
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
return hash;
|
|
858
|
+
}
|
|
859
|
+
if (extrinsic) {
|
|
860
|
+
if (!polkadotSigner) {
|
|
861
|
+
throw new Error("Polkadot signer must be provided");
|
|
862
|
+
}
|
|
863
|
+
const monitoringCallback = shouldListenToEvents ? createMonitoringCallback({
|
|
864
|
+
sourceAddress,
|
|
865
|
+
route,
|
|
866
|
+
extrinsic,
|
|
867
|
+
statusCallback,
|
|
868
|
+
onSourceFinalized,
|
|
869
|
+
onSourceError,
|
|
870
|
+
onDestinationFinalized,
|
|
871
|
+
onDestinationError
|
|
872
|
+
}) : void 0;
|
|
873
|
+
return sourcePolkadot.transfer(
|
|
874
|
+
sourceAddress,
|
|
875
|
+
extrinsic,
|
|
876
|
+
polkadotSigner,
|
|
877
|
+
monitoringCallback || statusCallback
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
throw new Error("Either contract or extrinsic must be provided");
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/sdk.ts
|
|
886
|
+
var DEFAULT_SERVICE = new ConfigService({ routes: xcmRoutesMap });
|
|
887
|
+
function Sdk({ configService, ecosystem } = {}) {
|
|
888
|
+
const service = configService ?? DEFAULT_SERVICE;
|
|
889
|
+
const assets = service.getEcosystemAssets(ecosystem);
|
|
890
|
+
return {
|
|
891
|
+
assets,
|
|
892
|
+
setAsset(asset) {
|
|
893
|
+
const sources = service.getSourceChains({ asset, ecosystem });
|
|
894
|
+
return {
|
|
895
|
+
sources,
|
|
896
|
+
setSource(source) {
|
|
897
|
+
const destinations = service.getDestinationChains({
|
|
898
|
+
asset,
|
|
899
|
+
source
|
|
900
|
+
});
|
|
901
|
+
return {
|
|
902
|
+
destinations,
|
|
903
|
+
setDestination(destination) {
|
|
904
|
+
const route = service.getAssetRoute({
|
|
905
|
+
asset,
|
|
906
|
+
source,
|
|
907
|
+
destination
|
|
908
|
+
});
|
|
909
|
+
return {
|
|
910
|
+
setAddresses({
|
|
911
|
+
sourceAddress,
|
|
912
|
+
destinationAddress
|
|
913
|
+
}) {
|
|
914
|
+
const sourceChain = service.getChain(source);
|
|
915
|
+
if (!EvmParachain2.isAnyParachain(sourceChain)) {
|
|
916
|
+
throw new Error(
|
|
917
|
+
"Source chain should be a Parachain or EvmParachain"
|
|
918
|
+
);
|
|
919
|
+
}
|
|
920
|
+
if (!EvmParachain2.isAnyParachain(route.destination.chain)) {
|
|
921
|
+
throw new Error(
|
|
922
|
+
"Destination chain should be a Parachain or EvmParachain"
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
return getTransferData({
|
|
926
|
+
route,
|
|
927
|
+
sourceAddress,
|
|
928
|
+
destinationAddress
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
async function getParachainBalances(chain, address, service = DEFAULT_SERVICE) {
|
|
940
|
+
const routes = service.getChainRoutes(chain).getRoutes();
|
|
941
|
+
const balances = await getAssetsBalances({
|
|
942
|
+
chain,
|
|
943
|
+
routes,
|
|
944
|
+
address
|
|
945
|
+
});
|
|
946
|
+
return balances;
|
|
947
|
+
}
|
|
948
|
+
export {
|
|
949
|
+
EvmService,
|
|
950
|
+
PolkadotService,
|
|
951
|
+
Sdk,
|
|
952
|
+
convertToChainDecimals,
|
|
953
|
+
createMonitoringCallback,
|
|
954
|
+
getAssetMin,
|
|
955
|
+
getAssetsBalances,
|
|
956
|
+
getBalance,
|
|
957
|
+
getContractFee,
|
|
958
|
+
getDestinationData,
|
|
959
|
+
getDestinationFee,
|
|
960
|
+
getDestinationFeeBalance,
|
|
961
|
+
getExistentialDeposit,
|
|
962
|
+
getExtrinsicFee,
|
|
963
|
+
getFee,
|
|
964
|
+
getMax,
|
|
965
|
+
getMin,
|
|
966
|
+
getParachainBalances,
|
|
967
|
+
getSourceData,
|
|
968
|
+
listenToDestinationEvents,
|
|
969
|
+
listenToSourceEvents,
|
|
970
|
+
processSourceEvents,
|
|
971
|
+
validateSovereignAccountBalances
|
|
972
|
+
};
|
|
2
973
|
//# sourceMappingURL=index.mjs.map
|