Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: depositing to and withdrawing from a remote ica account #10211

Merged
merged 3 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 223 additions & 0 deletions multichain-testing/test/deposit-withdraw-lca.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import anyTest from '@endo/ses-ava/prepare-endo.js';
import type { TestFn } from 'ava';
import { AmountMath } from '@agoric/ertp';
import { makeDoOffer } from '../tools/e2e-tools.js';
import { makeQueryClient } from '../tools/query.js';
import { commonSetup, SetupContextWithWallets } from './support.js';

const test = anyTest as TestFn<SetupContextWithWallets>;

const accounts = ['user1'];

const contractName = 'basicFlows';
const contractBuilder =
'../packages/builders/scripts/orchestration/init-basic-flows.js';

test.before(async t => {
const { deleteTestKeys, setupTestKeys, ...rest } = await commonSetup(t);
deleteTestKeys(accounts).catch();
const wallets = await setupTestKeys(accounts);
Comment on lines +17 to +19
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aside...

In Agoric/dapp-orchestration-basics#61 where I folded in your work on starship testing, I struggled a bit to get this commonSetup(t) stuff working. In order to be able to test it without re-deploying my contract for each iteration (or worse: standing up the whole cluster again), I factored out the ambient authority so I could inject mocks for quick ava testing.

See test('orca-multichain.test style usage', ...).
https://github.com/Agoric/dapp-orchestration-basics/blob/63f85352eaa73659d4cadbc1f17d48dd4095d98c/contract/test/agd-lib.test.js#L234

and test('deploy-cli style usage', ...)
https://github.com/Agoric/dapp-orchestration-basics/blob/main/contract/test/agd-lib.test.js#L214

Here's hoping we can migrate that back to support.js here in due course.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, that's a good approach for this problem. We added startContact in 3639831 a bit ago that ensures the contract is only installed once by querying vstorage

I wonder what the best path is for keeping testing tools in sync with minimal effort. Releases were something I'd floated in the past but it didn't seem to get much support.

t.context = { ...rest, wallets, deleteTestKeys };
const { startContract } = rest;
await startContract(contractName, contractBuilder);
});

test.after(async t => {
const { deleteTestKeys } = t.context;
deleteTestKeys(accounts);
});

test('Deposit IST to orchAccount and then withdraw', async t => {
const {
wallets,
provisionSmartWallet,
vstorageClient,
retryUntilCondition,
useChain,
} = t.context;

// Provision the Agoric smart wallet
const agoricAddr = wallets.user1;
const wdUser = await provisionSmartWallet(agoricAddr, {
BLD: 100n,
IST: 1000n,
});
t.log(`Provisioned Agoric smart wallet for ${agoricAddr}`);

const doOffer = makeDoOffer(wdUser);

// Create orchAccount
const makeAccountOfferId = `makeAccount-${Date.now()}`;
await doOffer({
id: makeAccountOfferId,
invitationSpec: {
source: 'agoricContract',
instancePath: [contractName],
callPipe: [['makeOrchAccountInvitation']],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

devex note: it would be nice if our contracts came with a supplementary module of constants so that client didn't have to come up with magic strings like this.

For example: https://github.com/Agoric/agoric-sdk/blob/master/packages/inter-protocol/src/clientSupport.js

Copy link
Member

@turadg turadg Oct 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

},
offerArgs: { chainName: 'agoric' },
proposal: {},
});

// Wait for the orchAccount to be created
const { offerToPublicSubscriberPaths } = await retryUntilCondition(
() => vstorageClient.queryData(`published.wallet.${agoricAddr}.current`),
({ offerToPublicSubscriberPaths }) =>
Object.fromEntries(offerToPublicSubscriberPaths)[makeAccountOfferId],
'makeAccount offer result is in vstorage',
);

// TODO type `offerToPublicSubscriberPaths` #10214 (OrchAccount)
const accountStoragePath = Object.fromEntries(offerToPublicSubscriberPaths)[
makeAccountOfferId
]!.account;
const lcaAddress = accountStoragePath.split('.').at(-1);
t.truthy(lcaAddress, 'Account address is in storage path');

// Get IST brand
const brands = await vstorageClient.queryData('published.agoricNames.brand');
const istBrand = Object.fromEntries(brands).IST;

// Deposit IST to orchAccount
const depositAmount = AmountMath.make(istBrand, 500n);
const depositOfferId = `deposit-${Date.now()}`;
await doOffer({
id: depositOfferId,
invitationSpec: {
source: 'continuing',
previousOffer: makeAccountOfferId,
invitationMakerName: 'Deposit',
},
offerArgs: {},
proposal: {
give: { Asset: depositAmount },
},
});

// Verify deposit
const apiUrl = await useChain('agoric').getRestEndpoint();
const queryClient = makeQueryClient(apiUrl);

const lcaBalanceAfterDeposit = await retryUntilCondition(
() => queryClient.queryBalance(lcaAddress, 'uist'),
({ balance }) => balance?.denom === 'uist' && balance?.amount === '500',
'Deposit reflected in localOrchAccount balance',
);
t.deepEqual(lcaBalanceAfterDeposit.balance, { denom: 'uist', amount: '500' });

// Withdraw IST from orchAccount
const withdrawAmount = AmountMath.make(istBrand, 300n);
const withdrawOfferId = `withdraw-${Date.now()}`;
await doOffer({
id: withdrawOfferId,
invitationSpec: {
source: 'continuing',
previousOffer: makeAccountOfferId,
invitationMakerName: 'Withdraw',
},
offerArgs: {},
proposal: {
want: { Asset: withdrawAmount },
},
});

// Verify withdrawal
const lcaBalanceAfterWithdraw = await retryUntilCondition(
() => queryClient.queryBalance(lcaAddress, 'uist'),
({ balance }) => balance?.denom === 'uist' && balance?.amount === '200',
'Withdraw reflected in localOrchAccount balance',
);
t.deepEqual(lcaBalanceAfterWithdraw.balance, {
denom: 'uist',
amount: '200',
});

// faucet - provision rebate - deposit + withdraw
const driverExpectedBalance = 1_000_000_000n + 250_000n - 500n + 300n;
const driverBalanceAfterWithdraw = await retryUntilCondition(
() => queryClient.queryBalance(agoricAddr, 'uist'),
({ balance }) =>
balance?.denom === 'uist' &&
balance?.amount === String(driverExpectedBalance),
'Withdraw reflected in driverAccount balance',
);
t.deepEqual(driverBalanceAfterWithdraw.balance, {
denom: 'uist',
amount: String(driverExpectedBalance),
});
});

test.todo('Deposit and Withdraw ATOM/OSMO to localOrchAccount via offer #9966');

test('Attempt to withdraw more than available balance', async t => {
const { wallets, provisionSmartWallet, vstorageClient, retryUntilCondition } =
t.context;

// Provision the Agoric smart wallet
const agoricAddr = wallets.user1;
const wdUser = await provisionSmartWallet(agoricAddr, {
BLD: 100n,
IST: 1000n,
});
t.log(`Provisioned Agoric smart wallet for ${agoricAddr}`);

const doOffer = makeDoOffer(wdUser);

// Create orchAccount
const makeAccountOfferId = `makeLocalAccount-${Date.now()}`;
await doOffer({
id: makeAccountOfferId,
invitationSpec: {
source: 'agoricContract',
instancePath: [contractName],
callPipe: [['makeOrchAccountInvitation']],
},
offerArgs: { chainName: 'agoric' },
proposal: {},
});

// Wait for the orchAccount to be created
const { offerToPublicSubscriberPaths } = await retryUntilCondition(
() => vstorageClient.queryData(`published.wallet.${agoricAddr}.current`),
({ offerToPublicSubscriberPaths }) =>
Object.fromEntries(offerToPublicSubscriberPaths)[makeAccountOfferId],
`${makeAccountOfferId} offer result is in vstorage`,
);

const accountStoragePath = Object.fromEntries(offerToPublicSubscriberPaths)[
makeAccountOfferId
]?.account;
const lcaAddress = accountStoragePath.split('.').at(-1);
t.truthy(lcaAddress, 'Account address is in storage path');

// Get IST brand
const brands = await vstorageClient.queryData('published.agoricNames.brand');
const istBrand = Object.fromEntries(brands).IST;

// Attempt to withdraw more than available balance
const excessiveWithdrawAmount = AmountMath.make(istBrand, 200n);
const withdrawOfferId = `withdraw-error-${Date.now()}`;
await doOffer({
id: withdrawOfferId,
invitationSpec: {
source: 'continuing',
previousOffer: makeAccountOfferId,
invitationMakerName: 'Withdraw',
},
offerArgs: {},
proposal: {
want: { Asset: excessiveWithdrawAmount },
},
});

// Verify that the withdrawal failed
const offerResult = await retryUntilCondition(
() => vstorageClient.queryData(`published.wallet.${agoricAddr}`),
({ status }) => status.id === withdrawOfferId && status.error !== undefined,
'Withdrawal offer error is in vstorage',
);
t.is(
offerResult.status.error,
'Error: One or more withdrawals failed ["[Error: cannot grab 200uist coins: 0uist is smaller than 200uist: insufficient funds]"]',
);
});
Loading
Loading