-
Notifications
You must be signed in to change notification settings - Fork 3
/
demo.ts
173 lines (151 loc) · 6.09 KB
/
demo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { ApiPromise, Keyring } from '@polkadot/api';
import { WsProvider } from '@polkadot/rpc-provider';
import { options } from '@sora-substrate/api';
import { CommonPrimitivesAssetId32 } from '@polkadot/types/lookup';
async function demo(): Promise<void> {
console.log('INITIALIZING API');
// NOTE: replace to use relevant endpoint: 'ws://localhost:9944/' for local, wss://ws.address.of.chain:9944/ for testnet
const provider = new WsProvider('ws://localhost:9944/');
const api = new ApiPromise(options({ provider }));
await api.isReady;
console.log('API IS READY, STARTING DEMO CALLS');
const keyring = new Keyring({ type: 'sr25519' });
// NOTE: replace to use specific keys
const root = keyring.addFromUri('//Alice', { name: 'Root' });
// const userA = keyring.addFromUri('//Bob', { name: 'UserA' });
// not a secret, specifically generated mnemonic for this demo
const userB = keyring.addFromMnemonic(
'shield shed shallow chase peace blade erosion poem health foil federal cushion',
{ name: 'UserB' }
);
console.log(root.address.toString());
// Creating types is not necessary, they will be automatically created if string is passed directly into function.
const XORAssetId = api.createType(
'AssetId',
'0x0200000000000000000000000000000000000000000000000000000000000000'
) as unknown as CommonPrimitivesAssetId32;
const VALAssetId = api.createType(
'AssetId',
'0x0200040000000000000000000000000000000000000000000000000000000000'
) as unknown as CommonPrimitivesAssetId32;
const PSWAPAssetId = api.createType(
'AssetId',
'0x0200050000000000000000000000000000000000000000000000000000000000'
) as unknown as CommonPrimitivesAssetId32;
const DAIAssetId = api.createType('AssetId', '0x0200060000000000000000000000000000000000000000000000000000000000');
// register pair
await submitExtrinsic(api, api.tx.tradingPair.register(0, XORAssetId, PSWAPAssetId), root, 'Enable Pair XOR-DOT');
// initialize pool
await submitExtrinsic(
api,
api.tx.poolXYK.initializePool(0, XORAssetId, PSWAPAssetId),
root,
'Initialize Pool for Pair XOR-DOT'
);
// mint xor and dot for account
await submitExtrinsic(
api,
api.tx.assets.mint(XORAssetId, userB.address, '105000000000000000000000000000000000'),
root,
'Mint XOR for User B'
);
await submitExtrinsic(
api,
api.tx.assets.mint(PSWAPAssetId, userB.address, '144000000000000000000000000000000000'),
root,
'Mint DOT for User B'
);
// add liquidity
await submitExtrinsic(
api,
api.tx.poolXYK.depositLiquidity(
0,
XORAssetId,
PSWAPAssetId,
'1000000000000000000',
'2000000000000000000',
'0',
'0'
),
userB,
'Add liquidity from User B'
);
// check balances
let balanceX = await (api.rpc as any).assets.freeBalance(userB.address, XORAssetId);
console.log('User B XOR FREE: ', balanceX.unwrap().balance.toString());
let balanceD = await (api.rpc as any).assets.freeBalance(userB.address, PSWAPAssetId);
console.log('User B DOT FREE: ', balanceD.unwrap().balance.toString());
let claimables = await (api.rpc as any).rewards.claimables('21Bc9f4a3d9Dc86f142F802668dB7D908cF0A636').toString();
console.log(claimables);
// get the liquidity sources list for path via liquidity proxy
let listEnabledSourcesForPath = (
await (api.rpc as any).liquidityProxy.listEnabledSourcesForPath(0, XORAssetId, VALAssetId)
).toJSON();
console.log(`listEnabledSourcesForPath ${XORAssetId} -> ${VALAssetId}`, listEnabledSourcesForPath);
// get the price via liquidity proxy
let quotedResult = await (api.rpc as any).liquidityProxy.quote(
0,
DAIAssetId,
XORAssetId,
'1000000000000000000',
'WithDesiredInput',
[],
'Disabled'
);
console.log('Quoted exchange DOT: ', quotedResult.unwrap().amount.toString());
console.log('Quoted exchange FEE: ', quotedResult.unwrap().fee.toString());
console.log('Quoted exchange rewards: ', quotedResult.unwrap().rewards.toJSON());
// perform swap via liquidity proxy
await submitExtrinsic(
api,
api.tx.liquidityProxy.swap(
0,
XORAssetId,
PSWAPAssetId,
{ WithDesiredInput: { desired_amount_in: '1000000000000000000', min_amount_out: '0' } },
[],
'Disabled'
),
userB,
'User B swaps'
);
// check user_b balance
let balance2 = await (api.rpc as any).assets.freeBalance(userB.address, PSWAPAssetId);
console.log('User B DOT FREE: ', balance2.unwrap().balance.toString());
}
async function inner_submitExtrinsic(api: ApiPromise, extrinsic: any, signer: any, finishCallback: any): Promise<void> {
// this is quick example, refer to https://polkadot.js.org/docs/api/cookbook/tx and https://polkadot.js.org/docs/api/start/api.tx.subs
const unsub = await extrinsic.signAndSend(signer, (result: any) => {
console.log(`Current status is ${result.status}`);
if (result.status.isInBlock) {
console.log(`Transaction included at blockHash ${result.status.asInBlock}`);
} else if (result.status.isFinalized) {
console.log(`Transaction finalized at blockHash ${result.status.asFinalized}`);
result.events.forEach(({ phase, event: { data, method, section } }: any) => {
console.log(`\t' ${phase}: ${section}.${method}:: ${data}`);
if (section === 'system' && method === 'ExtrinsicFailed') {
const [error] = data;
if (error.isModule) {
const decoded = api.registry.findMetaError(error.asModule);
const { docs, name, section } = decoded;
console.log(`${section}.${name}: ${docs.join(' ')}`);
} else {
// Other, CannotLookup, BadOrigin, no extra info
console.log(error.toString());
}
}
});
unsub();
finishCallback();
}
});
}
async function submitExtrinsic(api: ApiPromise, extrinsic: any, signer: any, debugMessage = ''): Promise<void> {
console.log(`\nSubmit extrinsic: ${debugMessage}\n`);
return new Promise((resolve, _reject) => {
inner_submitExtrinsic(api, extrinsic, signer, resolve);
});
}
demo()
.catch(console.error)
.finally(() => process.exit());