Skip to content
Open
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
4 changes: 2 additions & 2 deletions examples/ts/share-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ bitgo.register(coin, Tbtc.createInstance);
const walletId = '';

// TODO: set BitGo account email of wallet share recipient
const recipient = null;
const recipient = "recipient_email";

// TODO: set share permissions as a comma-separated list
// Valid permissions to choose from are: view, spend, manage, admin
const perms = 'view';

// TODO: provide the passphrase for the wallet being shared
const passphrase = null;
const passphrase = "passhrase";

async function main() {
const wallet = await bitgo.coin(coin).wallets().get({ id: walletId });
Expand Down
11 changes: 5 additions & 6 deletions modules/express/src/clientRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -687,11 +687,11 @@ export function handleV2CreateLocalKeyChain(req: ExpressApiRouteRequest<'express
* handle wallet share
* @param req
*/
async function handleV2ShareWallet(req: express.Request) {
export async function handleV2ShareWallet(req: ExpressApiRouteRequest<'express.v2.wallet.share', 'post'>) {
const bitgo = req.bitgo;
const coin = bitgo.coin(req.params.coin);
const wallet = await coin.wallets().get({ id: req.params.id });
return wallet.shareWallet(req.body);
const coin = bitgo.coin(req.decoded.coin);
const wallet = await coin.wallets().get({ id: req.decoded.id });
return wallet.shareWallet(req.decoded);
}

/**
Expand Down Expand Up @@ -1619,8 +1619,7 @@ export function setupAPIRoutes(app: express.Application, config: Config): void {

router.post('express.v2.wallet.createAddress', [prepareBitGo(config), typedPromiseWrapper(handleV2CreateAddress)]);

// share wallet
app.post('/api/v2/:coin/wallet/:id/share', parseBody, prepareBitGo(config), promiseWrapper(handleV2ShareWallet));
router.post('express.v2.wallet.share', [prepareBitGo(config), typedPromiseWrapper(handleV2ShareWallet)]);
app.post(
'/api/v2/:coin/walletshare/:id/acceptshare',
parseBody,
Expand Down
4 changes: 4 additions & 0 deletions modules/express/src/typedRoutes/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { PostCreateAddress } from './v2/createAddress';
import { PutFanoutUnspents } from './v1/fanoutUnspents';
import { PostOfcSignPayload } from './v2/ofcSignPayload';
import { PostWalletRecoverToken } from './v2/walletRecoverToken';
import { PostShareWallet } from './v2/shareWallet';

export const ExpressApi = apiSpec({
'express.ping': {
Expand Down Expand Up @@ -100,6 +101,9 @@ export const ExpressApi = apiSpec({
'express.v2.wallet.recovertoken': {
post: PostWalletRecoverToken,
},
'express.v2.wallet.share': {
post: PostShareWallet,
},
});

export type ExpressApi = typeof ExpressApi;
Expand Down
88 changes: 88 additions & 0 deletions modules/express/src/typedRoutes/api/v2/shareWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import * as t from 'io-ts';
import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http';
import { BitgoExpressError } from '../../schemas/error';
import { ShareState, ShareWalletKeychain } from '../../schemas/wallet';

/**
* Path parameters for sharing a wallet
*/
export const ShareWalletParams = {
/** Coin ticker / chain identifier */
coin: t.string,
/** Wallet ID */
id: t.string,
} as const;

/**
* Request body for sharing a wallet
*/
export const ShareWalletBody = {
/** Recipient email address (required) */
email: t.string,
/** Permissions string, e.g., "view,spend" (required) */
permissions: t.string,
/** Wallet passphrase used to derive shared key when needed */
walletPassphrase: optional(t.string),
/** Optional message to include with the share */
message: optional(t.string),
/** If true, allows sharing without a keychain */
reshare: optional(t.boolean),
/** If true, skips sharing the wallet keychain with the recipient */
skipKeychain: optional(t.boolean),
/** If true, suppresses email notification to the recipient */
disableEmail: optional(t.boolean),
} as const;

/**
* Response for sharing a wallet
*/
export const ShareWalletResponse200 = t.intersection([
t.type({
/** Wallet share id */
id: t.string,
/** Coin of the wallet */
coin: t.string,
/** Wallet id */
wallet: t.string,
/** Id of the sharer */
fromUser: t.string,
/** Id of the recipient */
toUser: t.string,
/** Comma-separated list of privileges for wallet */
permissions: t.string,
}),
t.partial({
/** Wallet label */
walletLabel: t.string,
/** User-readable message */
message: t.string,
/** Share state */
state: ShareState,
/** Enterprise id, if applicable */
enterprise: t.string,
/** Pending approval id, if one was generated */
pendingApprovalId: t.string,
/** Included if shared with spend permission */
keychain: ShareWalletKeychain,
}),
]);

export const ShareWalletResponse = {
200: ShareWalletResponse200,
400: BitgoExpressError,
} as const;

/**
* Share this wallet with another BitGo user.
*
* @operationId express.v2.wallet.share
*/
export const PostShareWallet = httpRoute({
path: '/api/v2/{coin}/wallet/{id}/share',
method: 'POST',
request: httpRequest({
params: ShareWalletParams,
body: ShareWalletBody,
}),
response: ShareWalletResponse,
});
17 changes: 17 additions & 0 deletions modules/express/src/typedRoutes/schemas/wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as t from 'io-ts';

export const ShareState = t.union([
t.literal('pendingapproval'),
t.literal('active'),
t.literal('accepted'),
t.literal('canceled'),
t.literal('rejected'),
]);

export const ShareWalletKeychain = t.partial({
pub: t.string,
encryptedPrv: t.string,
fromPubKey: t.string,
toPubKey: t.string,
path: t.string,
});
98 changes: 98 additions & 0 deletions modules/express/test/unit/clientRoutes/shareWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import * as sinon from 'sinon';
import 'should-http';
import 'should-sinon';
import '../../lib/asserts';
import nock from 'nock';
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
import { BitGo } from 'bitgo';
import { BaseCoin, Wallets, Wallet, decodeOrElse, common } from '@bitgo/sdk-core';
import { ExpressApiRouteRequest } from '../../../src/typedRoutes/api';
import { handleV2ShareWallet } from '../../../src/clientRoutes';
import { ShareWalletResponse } from '../../../src/typedRoutes/api/v2/shareWallet';

describe('Share Wallet (typed handler)', () => {
let bitgo: TestBitGoAPI;

before(async function () {
if (!nock.isActive()) {
nock.activate();
}
bitgo = TestBitGo.decorate(BitGo, { env: 'test' });
bitgo.initializeTestVars();
nock.disableNetConnect();
nock.enableNetConnect('127.0.0.1');
});

after(() => {
if (nock.isActive()) {
nock.restore();
}
});

it('should call shareWallet (no stub), mock BitGo HTTP, and return typed response', async () => {
const coin = 'tbtc';
const walletId = '59cd72485007a239fb00282ed480da1f';
const email = '[email protected]';
const permissions = 'view';
const message = 'hello';

const baseCoin = bitgo.coin(coin);
const walletData = {
id: walletId,
coin: coin,
keys: ['k1', 'k2', 'k3'],
coinSpecific: {},
multisigType: 'onchain',
type: 'hot',
};
const realWallet = new Wallet(bitgo, baseCoin, walletData);
const coinStub = sinon.createStubInstance(BaseCoin, {
wallets: sinon.stub<[], Wallets>().returns({
get: sinon.stub<[any], Promise<Wallet>>().resolves(realWallet),
} as any),
});

const stubBitgo = sinon.createStubInstance(BitGo, { coin: sinon.stub<[string]>().returns(coinStub) });

const bgUrl = common.Environments[bitgo.getEnv()].uri;
const getSharingKeyNock = nock(bgUrl).post('/api/v1/user/sharingkey', { email }).reply(200, { userId: 'u1' });
const shareResponse = {
id: walletId,
coin,
wallet: walletId,
fromUser: 'u0',
toUser: 'u1',
permissions,
message,
state: 'active',
};
const createShareNock = nock(bgUrl)
.post(`/api/v2/${coin}/wallet/${walletId}/share`, (body) => {
body.user.should.equal('u1');
body.permissions.should.equal(permissions);
body.skipKeychain.should.equal(true);
if (message) body.message.should.equal(message);
return true;
})
.reply(200, shareResponse);

const req = {
bitgo: stubBitgo,
decoded: {
coin,
id: walletId,
email,
permissions,
message,
},
} as unknown as ExpressApiRouteRequest<'express.v2.wallet.share', 'post'>;

const res = await handleV2ShareWallet(req);
decodeOrElse('ShareWalletResponse200', ShareWalletResponse[200], res, (errors) => {
throw new Error(`Response did not match expected codec: ${errors}`);
});

getSharingKeyNock.isDone().should.be.true();
createShareNock.isDone().should.be.true();
});
});