-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathcontract.ts
278 lines (250 loc) · 11.4 KB
/
contract.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { expect } from 'chai';
import { before, describe, it } from 'mocha';
import { assertNotNull, InputNumber } from '../utils';
import { getSdk } from '.';
import {
ArgumentError, NodeInvocationError, Encoded, DRY_RUN_ACCOUNT,
messageToHash, UnexpectedTsError, AeSdk, Contract, ContractMethodsBase,
} from '../../src';
const identitySourceCode = `
contract Identity =
entrypoint getArg(x : int) = x
`;
interface IdentityContractApi extends ContractMethodsBase {
getArg: (x: InputNumber) => bigint;
}
describe('Contract', () => {
let aeSdk: AeSdk;
let bytecode: Encoded.ContractBytearray;
let identityContract: Contract<IdentityContractApi>;
let deployed: Awaited<ReturnType<Contract<{}>['$deploy']>>;
before(async () => {
aeSdk = await getSdk(2);
});
it('deploys precompiled bytecode', async () => {
identityContract = await aeSdk
.initializeContract({ bytecode, sourceCode: identitySourceCode });
expect(await identityContract.$deploy([])).to.have.property('address');
});
it('throws exception if deploy deposit is not zero', async () => {
delete identityContract.$options.address;
await expect(identityContract.$deploy([], { deposit: 10 })).to.be.rejectedWith(
ArgumentError,
'deposit should be equal 0 (because is not refundable), got 10 instead',
);
});
it('deploys static', async () => {
const res = await identityContract.$deploy([], { callStatic: true });
expect(res.result).to.have.property('gasUsed');
expect(res.result).to.have.property('returnType');
});
it('Verify signature of 32 bytes in Sophia', async () => {
const signContract = await aeSdk.initializeContract<{
verify: (data: Uint8Array, pub: Encoded.AccountAddress, sig: Uint8Array) => boolean;
}>({
sourceCode:
'contract Sign ='
+ '\n entrypoint verify (data: bytes(32), pub: address, sig: signature): bool ='
+ '\n Crypto.verify_sig(data, pub, sig)',
});
await signContract.$deploy([]);
const data = Buffer.from(new Array(32).fill(0).map((_, idx) => idx ** 2));
const signature = await aeSdk.sign(data);
expect((await signContract.verify(data, aeSdk.address, signature)).decodedResult)
.to.be.equal(true);
});
it('Verify message in Sophia', async () => {
const signContract = await aeSdk.initializeContract<{
message_to_hash: (message: string) => Uint8Array;
verify: (message: string, pub: Encoded.AccountAddress, sig: Uint8Array) => boolean;
}>({
sourceCode:
'include "String.aes"'
+ '\n'
+ '\ncontract Sign ='
+ '\n entrypoint int_to_binary (i: int): string ='
+ '\n switch(Char.from_int(i))'
+ '\n None => abort("Int is too big")'
+ '\n Some(c) => String.from_list([c])'
+ '\n'
+ '\n entrypoint includes (str: string, pat: string): bool ='
+ '\n switch(String.contains(str, pat))'
+ '\n None => false'
+ '\n Some(_) => true'
+ '\n'
+ '\n entrypoint message_to_hash (message: string): hash ='
+ '\n let prefix = "aeternity Signed Message:\\n"'
+ '\n let prefixBinary = String.concat(int_to_binary(String.length(prefix)), prefix)'
+ '\n let messageBinary = String.concat(int_to_binary(String.length(message)), message)'
+ '\n Crypto.blake2b(String.concat(prefixBinary, messageBinary))'
+ '\n'
+ '\n entrypoint verify (message: string, pub: address, sig: signature): bool ='
+ '\n require(includes(message, "H"), "Invalid message")'
+ '\n Crypto.verify_sig(message_to_hash(message), pub, sig)',
});
await signContract.$deploy([]);
await Promise.all(['Hello', 'H'.repeat(127)].map(async (message) => {
expect((await signContract.message_to_hash(message)).decodedResult)
.to.be.eql(messageToHash(message));
const signature = await aeSdk.signMessage(message);
expect((await signContract.verify(message, aeSdk.address, signature)).decodedResult)
.to.be.equal(true);
}));
});
it('Deploy and call contract on specific account', async () => {
delete identityContract.$options.address;
const onAccount = aeSdk.accounts[aeSdk.addresses()[1]];
const accountBefore = identityContract.$options.onAccount;
identityContract.$options.onAccount = onAccount;
deployed = await identityContract.$deploy([]);
if (deployed?.result?.callerId == null) throw new UnexpectedTsError();
expect(deployed.result.callerId).to.be.equal(onAccount.address);
let { result } = await identityContract.getArg(42, { callStatic: true });
assertNotNull(result);
expect(result.callerId).to.be.equal(onAccount.address);
result = (await identityContract.getArg(42, { callStatic: false })).result;
assertNotNull(result);
expect(result.callerId).to.be.equal(onAccount.address);
identityContract.$options.onAccount = accountBefore;
});
it('Call-Static deploy transaction', async () => {
const { result } = await identityContract.$deploy([], { callStatic: true });
assertNotNull(result);
result.should.have.property('gasUsed');
result.should.have.property('returnType');
});
it('Call-Static deploy transaction on specific hash', async () => {
const hash = (await aeSdk.api.getTopHeader()).hash as Encoded.MicroBlockHash;
const { result } = await identityContract.$deploy([], { callStatic: true, top: hash });
assertNotNull(result);
result.should.have.property('gasUsed');
result.should.have.property('returnType');
});
it('throws error on deploy', async () => {
const ct = await aeSdk.initializeContract({
sourceCode:
'contract Foo =\n'
+ ' entrypoint init() = abort("CustomErrorMessage")',
});
await expect(ct.$deploy([])).to.be.rejectedWith(NodeInvocationError, 'Invocation failed: "CustomErrorMessage"');
});
it('throws errors on method call', async () => {
const ct = await aeSdk.initializeContract<{
failWithoutMessage: (x: Encoded.AccountAddress) => void;
failWithMessage: () => void;
}>({
sourceCode:
'contract Foo =\n'
+ ' payable stateful entrypoint failWithoutMessage(x : address) = Chain.spend(x, 1000000000)\n'
+ ' payable stateful entrypoint failWithMessage() =\n'
+ ' abort("CustomErrorMessage")',
});
await ct.$deploy([]);
await expect(ct.failWithoutMessage(aeSdk.address))
.to.be.rejectedWith('Invocation failed');
await expect(ct.failWithMessage())
.to.be.rejectedWith('Invocation failed: "CustomErrorMessage"');
});
it('Dry-run without accounts', async () => {
const sdk = await getSdk(0);
const contract = await sdk.initializeContract<IdentityContractApi>({
sourceCode: identitySourceCode, address: deployed.address,
});
const { result } = await contract.getArg(42);
assertNotNull(result);
result.callerId.should.be.equal(DRY_RUN_ACCOUNT.pub);
});
it('Dry-run at specific height', async () => {
const contract = await aeSdk.initializeContract<{ call: () => void }>({
sourceCode: 'contract Callable =\n'
+ ' record state = { wasCalled: bool }\n'
+ '\n'
+ ' entrypoint init() : state = { wasCalled = false }\n'
+ '\n'
+ ' stateful entrypoint call() =\n'
+ ' require(!state.wasCalled, "Already called")\n'
+ ' put(state{ wasCalled = true })\n',
});
await contract.$deploy([]);
await aeSdk.awaitHeight(await aeSdk.getHeight() + 1);
const beforeKeyBlockHeight = await aeSdk.getHeight();
await aeSdk.spend(1, aeSdk.address);
const topHeader = await aeSdk.api.getTopHeader();
const beforeKeyBlockHash = topHeader.prevKeyHash as Encoded.KeyBlockHash;
const beforeMicroBlockHash = topHeader.hash as Encoded.MicroBlockHash;
expect(beforeKeyBlockHash).to.satisfy((s: string) => s.startsWith('kh_'));
expect(beforeMicroBlockHash).to.satisfy((s: string) => s.startsWith('mh_'));
await contract.call();
await expect(contract.call()).to.be.rejectedWith('Already called');
await contract.call({ callStatic: true, top: beforeMicroBlockHash });
await contract.call({ callStatic: true, top: beforeKeyBlockHash });
await contract.call({ callStatic: true, top: beforeKeyBlockHeight });
});
it('call contract/deploy with waitMined: false', async () => {
delete identityContract.$options.address;
const deployInfo = await identityContract.$deploy([], { waitMined: false });
assertNotNull(deployInfo.transaction);
await aeSdk.poll(deployInfo.transaction);
expect(deployInfo.result).to.be.equal(undefined);
deployInfo.txData.should.not.be.equal(undefined);
const result = await identityContract.getArg(42, { callStatic: false, waitMined: false });
expect(result.result).to.be.equal(undefined);
result.txData.should.not.be.equal(undefined);
await aeSdk.poll(result.hash as Encoded.TxHash);
});
it('calls deployed contracts static', async () => {
const result = await identityContract.getArg(42, { callStatic: true });
expect(result.decodedResult).to.be.equal(42n);
});
it('initializes contract state', async () => {
const contract = await aeSdk.initializeContract<{
init: (a: string) => void;
retrieve: () => string;
}>({
sourceCode:
'contract StateContract =\n'
+ ' record state = { value: string }\n'
+ ' entrypoint init(value) : state = { value = value }\n'
+ ' entrypoint retrieve() : string = state.value',
});
const data = 'Hello World!';
await contract.$deploy([data]);
expect((await contract.retrieve()).decodedResult).to.be.equal(data);
});
describe('Namespaces', () => {
const contractWithLibSourceCode = (
'include "testLib"\n'
+ 'contract ContractWithLib =\n'
+ ' entrypoint sumNumbers(x: int, y: int) : int = TestLib.sum(x, y)'
);
let contract: Contract<{ sumNumbers: (x: number, y: number) => bigint }>;
it('Can compiler contract with external deps', async () => {
contract = await aeSdk.initializeContract({
sourceCode: contractWithLibSourceCode,
fileSystem: {
testLib:
'namespace TestLib =\n'
+ ' function sum(x: int, y: int) : int = x + y',
},
});
expect(await contract.$compile()).to.satisfy((b: string) => b.startsWith('cb_'));
});
it('Throw error when try to compile contract without providing external deps', async () => {
await expect(aeSdk.initializeContract({ sourceCode: contractWithLibSourceCode }))
.to.be.rejectedWith('Couldn\'t find include file');
});
it('Can deploy contract with external deps', async () => {
const deployInfo = await contract.$deploy([]);
expect(deployInfo).to.have.property('address');
const deployedStatic = await contract.$deploy([], { callStatic: true });
expect(deployedStatic.result).to.have.property('gasUsed');
expect(deployedStatic.result).to.have.property('returnType');
});
it('Can call contract with external deps', async () => {
expect((await contract.sumNumbers(1, 2, { callStatic: false })).decodedResult)
.to.be.equal(3n);
expect((await contract.sumNumbers(1, 2, { callStatic: true })).decodedResult)
.to.be.equal(3n);
});
});
});